unity中简单的移动方法

在游戏开发中通常以wasd和方向键还有鼠标来控制玩家的移动
在这里我介绍三种以wasd和方向键控制玩家移动的方法
下面介绍的时候我会直接给出代码 然后解释

1.利用刚体(Rigidbody)

 public float speed = 5f;
    private Rigidbody rigidbody;
    private void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
    }
    private void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
        rigidbody.velocity = new Vector3(h, 0, v) *Time.deltaTime  * speed;
    }

2.利用Translate方法

    public float speed = 5f;
    private void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
        transform.Translate(new Vector3(h, 0, v) * Time.deltaTime * speed);
    }

在这个方法中需要了解Translate(方向速度Time.deltatime);

3.利用movement

 private int speed = 5;
    Vector3 movement;
    private Rigidbody rigidbody;
    private void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
    }
    private void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
        Move(h, v);
    }
    private void Move(float h, float v)
    {
        movement.Set(h, 0, v);
        movement = movement.normalized * Time.deltaTime * speed;//计算
        rigidbody.MovePosition(transform.position + movement);//移动
    }

以上三个方法都需要轴的输入
这个必须记住

发布了52 篇原创文章 · 获赞 47 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44302602/article/details/96874181
今日推荐