c# - Unity - 如何沿对角线移动

标签 c# unity3d

我已经定义了向前移动和向左移动。我如何使它对角线(向左和向上移动)?感谢转发。

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/

相关文章:

xcode - 根据韩国的开发人员设置配置,不允许用户查看应用程序?

unity3d - 何时使用 Photon Networking 主客户端?

unity3d - 统一与 Sceneform 功能/用例中的 ARCore?

c# - 所需关键字的正则表达式?

c# - 序列化和反序列化类中的静态成员?

c# - 计算 3d 空间中两点之间的角度

c# - Unity 2D Mouse Zoom,但放大到鼠标点的位置

c# - C# 中 PKCS11Interop 库的线程安全使用

c# - 有什么方法可以模拟直接在方法中创建新连接的 Entity Framework 调用

c# - 类型 'MyApp' 已经包含 'MystatusBar' 的定义