自分がプレイする物体を自由に動かせるようになりたい。

 

プレイする為のオブジェクトを入れそれに何かコンポーネントを入れスプリクトを作ってどうとか…

 

検索すればある程度のことは出てくるということで調べてやってみました。

 

 

UNITYを開き

3Dでプロジェクトを作成

 

導入したGameObject

Plane(平面)、Sphere(スフィア)、Cube(キューブ)

※Planeは床、Sphereを動かしたいプレイヤー、Cubeは障害物として設置しました。

 

オブジェクトに入れたコンポーネント

Plane、Cubeは既存のものをそのままに

Spehereには[Character Controller]、[Rigidbody]、[C#Script]を導入

 

移動、ジャンプの仕方を検索して組み合わせた結果

SpehereのC#スクリプトの内容は下記のようになりました。

 

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Player : MonoBehaviour
  6. {
  7.  
  8.     public float speed = 5.0f;
  9.     float moveX = 0f;
  10.     float moveZ = 0f;
  11.  
  12.     private CharacterController controller;
  13.     private Vector3 moveDirection;
  14.  
  15.  
  16.     void Start()
  17.     {
  18.  
  19.         // コンポーネントCharacterControllerの取得
  20.         controller = GetComponent<CharacterController>();
  21.  
  22.     }
  23.  
  24.  
  25.     void Update()
  26.     {
  27.         // オブジェクトの移動
  28.         moveX = Input.GetAxis("Horizontal") * speed;
  29.         moveZ = Input.GetAxis("Vertical") * speed;
  30.         Vector3 direction = new Vector3(moveX, 0, moveZ);
  31.  
  32.         controller.SimpleMove(direction);
  33.  
  34.  
  35.         // もし着地していたら
  36.         if (controller.isGrounded)
  37.         {
  38.             // スペースキーの入力が入るとジャンプ
  39.             if (Input.GetKeyDown(KeyCode.Space))
  40.             {
  41.                 // ジャンプ力
  42.                 moveDirection.y = 10;
  43.             }
  44.         }
  45.  
  46.         // オブジェクトの重力
  47.         moveDirection.y -= 10 * Time.deltaTime;
  48.  
  49.         // オブジェクトを動かす処理
  50.         controller.Move(moveDirection * Time.deltaTime);
  51.     }
  52.  
  53.  
  54. }
 
 
プレイしてみたらこんな感じになりました。