うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】オブジェクトを今向いている方向に前後左右移動させる

transform.rotation に移動ベクトルを乗算すると今向いている向きから前後左右に移動させることができる

using UnityEngine;
 
public class PlayerController : MonoBehaviour
{
    [SerializeField]
    private float _speed = 1f;
     
    private void Update()
    {
        if (Input.anyKey)
        {
            var velocity = Vector3.zero;
            if (Input.GetKey(KeyCode.W))
            {
                velocity.z = _speed;
            }
            if (Input.GetKey(KeyCode.A))
            {
                velocity.x = -_speed;
            }
            if (Input.GetKey(KeyCode.S))
            {
                velocity.z = -_speed;
            }
            if (Input.GetKey(KeyCode.D))
            {
                velocity.x = _speed;
            }

            if (velocity.x != 0 || velocity.z != 0)
            {
                transform.position += transform.rotation * velocity;
            }
        }
    }
}