我已经定义了向前移动和向左移动.如何对角(左移和上移)?谢谢你的转发.
if (Input.GetKey(KeyCode.W))
{
player.MovePosition(transform.position + transform.forward * speed * Time.deltaTime);
}
if(Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A))
{
???
}
if (Input.GetKey(KeyCode.A))
{
player.MovePosition(transform.position - transform.right * speed * Time.deltaTime);
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,你的当前代码由于一个怪癖而无法工作Rigidbody.MovePosition()- 它的文档没有提到它,但是对于方法的2D变体,它提到了
实际位置更改仅在下一次物理更新期间发生,因此重复调用此方法而不等待下一次物理更新将导致使用最后一次调用.
因此,虽然在按下两个键时都会输入两个if语句,但只有MovePosition()最后一个键才能生效.
为了解决这个问题,我的建议是计算一个组合的运动矢量而不是立即调用MovePosition().然后,在末尾应用运动矢量,因此您只需要调用MovePosition()一次:
Vector3 totalMovement = Vector3.zero;
if (Input.GetKey(KeyCode.W))
{
totalMovement += transform.forward;
}
if (Input.GetKey(KeyCode.A))
{
totalMovement -= transform.right;
}
// To ensure same speed on the diagonal, we ensure its magnitude here instead of earlier
player.MovePosition(transform.position + totalMovement.normalized * speed * Time.deltaTime);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!如果您有任何疑问,请告诉我.