プレイヤーを動かす(CharacterController)

CharacterControllerを使用してプレイヤーを操作しよう

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
  public float walkSpeed = 6.0f;
  public float jumpSpeed = 8.0f;
  public float gravity = Physics.gravity.y;

  Vector3 moveDirection = Vector3.zero;

  void Update() {
    CharacterController controller = GetComponent<CharacterController>();
    if (controller.isGrounded) {
      moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
      moveDirection = transform.TransformDirection(moveDirection);
      moveDirection *= walkSpeed;
      if (Input.GetButton("Jump")) {
        moveDirection.y = jumpSpeed;
      }
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
  }
}