我已经定义了向前移动和向左移动。我如何使它对角线(向左和向上移动)?感谢转发。
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);
}
最佳答案
值得注意的是,由于 Rigidbody.MovePosition()
的怪癖,您当前的代码无法正常工作 - 它的文档没有提及它,但对于 the 2D variant of the method , 提到了
the actual position change will only occur during the next physics update therefore calling this method repeatedly without waiting for the next physics update will result in the last call being used.
所以虽然两个键同时按下都会进入两个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);
希望对您有所帮助!如果您有任何问题,请告诉我。
关于c# - Unity - 如何沿对角线移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44530235/