Created
September 19, 2017 07:01
-
-
Save MasashiWada/f3aad493c844ab747eaac8a8fe5854b1 to your computer and use it in GitHub Desktop.
CharacterControllerを使った移動 (original: https://gist.github.com/vend9520/76457eed9915805e199b25dc653d5df3#file-movecharacter-cs)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Collections; | |
| public class MoveCharacter : MonoBehaviour { | |
| public float speed = 3.0F; //移動速度 | |
| public float jumpSpeed = 8.0F; //ジャンプ速度 | |
| public float gravity = 20.0F; //重力 | |
| public GameObject charaobj; //キャラクターオブジェクト | |
| public GameObject camobj; //カメラオブジェクト | |
| private Animator animator; | |
| private Vector3 moveDirection = Vector3.zero; //移動方向 | |
| void Start() { | |
| //キャラクターにアタッチされているAnimatorを取得する | |
| animator = charaobj.GetComponent<Animator>(); | |
| } | |
| void Update() { | |
| CharacterController controller = GetComponent<CharacterController>(); | |
| //CharacterControllerのisGroundedで接地判定 | |
| if (controller.isGrounded) { | |
| //入力値にカメラのオイラー角を掛ける事で、カメラの角度に応じた移動方向に補正する | |
| moveDirection = Quaternion.Euler(0, camobj.transform.localEulerAngles.y, 0) * new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); | |
| //移動方向をローカルからワールド空間に変換する | |
| moveDirection = transform.TransformDirection(moveDirection); | |
| //移動速度を掛ける | |
| moveDirection *= speed; | |
| if (Input.GetButton("Jump")) { | |
| //ジャンプボタンが押下された場合、y軸方向への移動を追加する | |
| moveDirection.y = jumpSpeed; | |
| } | |
| } | |
| //水平移動分のベクトルを取得する(アニメーションの制御用) | |
| var moveVector = new Vector3(moveDirection.x, 0, moveDirection.z); | |
| //ベクトルから速度を取得し(magnitude)、アニメーターに渡す | |
| animator.SetFloat("speed", moveVector.magnitude / speed); | |
| //移動時にのみキャラを回転させる(待機時に方向が固定されず前方を向いてしまうため) | |
| if (moveVector.magnitude > 0) { | |
| //移動方向に向けてキャラを回転させる | |
| charaobj.transform.rotation = Quaternion.LookRotation(moveVector); | |
| } | |
| //y軸方向への移動に重力を加える | |
| moveDirection.y -= gravity * Time.deltaTime; | |
| //CharacterControllerを移動させる | |
| controller.Move(moveDirection * Time.deltaTime); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment