Unity 控制物体移动的方法

方法一: 获取键盘输入的值

void KeyBoardMove()
    {
        if (Input.GetKey(KeyCode.D))
        {
            transform.position += Vector3.right * Time.deltaTime * _Speed;
        }
        if (Input.GetKey(KeyCode.A))
        {
            transform.position += Vector3.left * Time.deltaTime * _Speed;
        }
        if (Input.GetKey(KeyCode.W))
        {
            transform.position += Vector3.forward * Time.deltaTime * _Speed;
        }

        if (Input.GetKey(KeyCode.S))
        {
            transform.position += Vector3.back * Time.deltaTime * _Speed;
        }
    }

方法二:轴向移动

void AxisMove()
    {
        transform.position = new Vector3(transform.position.x + Input.GetAxis("Horizontal") * 0.1f, transform.position.y, transform.position.z + Input.GetAxis("Vertical") * 0.1f);
        //Input.GetAxis("Horizontal");//A D 左右
        //Input.GetAxis("Vertical"); //W S  前后
    }

方法三:给物体添加刚体  然后施力让物体运动

void ForceMove()
    {
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");
        if (h == 0 && v == 0)
        {
            return;
        }
        _rigidbody.AddForce(new Vector3(h, 0, v) * _force * 0.3f);
    }

 

你可能感兴趣的:(Unity)