【问题标题】:RigidBody MovePosition lags behind another RigidBodyRigidBody MovePosition 落后于另一个 RigidBody
【发布时间】:2019-11-29 08:31:23
【问题描述】:

我正在做一个 VR 游戏,而相机是通过 RigidBody 控制的:

private void FixedUpdate() {
   Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
   ...
   rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
}

现在我想移动玩家的手,它也有一个刚体,所以我这样做:

private void FixedUpdate() {
    GetComponent<Rigidbody>().MovePosition(mainPlayer.transform.TransformPoint(controller));
    GetComponent<Rigidbody>().MoveRotation(mainPlayer.transform.rotation * rot);
}

当我使用摇杆移动主角时,手确实会随之移动,但它明显滞后。我知道游戏引擎和物理引擎的运行循环之间的区别,但仍然无法理解。

编辑:

我的猜测是,当我在相机上执行 AddForce 时,直到调用了所有 FixedUpdates 之后,变换才会更新,因此手无法访问最新的变换。

而我能解决它的唯一方法是通过一些智能关节设置。

【问题讨论】:

标签: unity3d


【解决方案1】:

这是发生了什么:

当我在 FixedUpdate 中的相机上调用 AddForce 时,变换直到稍后才会改变,毕竟调用了所有 FixedUpdates 并且物理引擎继续进行模拟计算。

这就是为什么当我在手中打电话给MovePosition 时,它总是落后一个物理刻度。

我通过预测应该在当前物理框架中的位置来修复它。

    //Get the camera velocity after `AddForce`
    cameraVelocity = cameraVelocity * Time.fixedDeltaTime;

    //I know the velocity so I know where the camera will end up once the physics engine sets all the transforms
    //I'm pseudo-simulating the current physics step

    mainPlayer.transform.position += vel;

    GetComponent<Rigidbody>().MovePosition(mainPlayer.transform.TransformPoint(controller));
    GetComponent<Rigidbody>().MoveRotation(mainPlayer.transform.rotation * rot);

    mainPlayer.transform.position -= vel;

现在一切都很顺利!

【讨论】:

    【解决方案2】:

    您应该将您的逻辑从固定更新中移开,因为它不是每帧都调用它,有时它会每帧发生两次,有时每两帧发生一次。

    FixedUpdate 的调用频率通常比 Update 高。如果帧速率低,则每帧可以调用多次,如果帧速率高,则可能根本不会在帧之间调用。所有物理计算和更新都在 FixedUpdate 之后立即发生。在 FixedUpdate 中应用移动计算时,您不需要将值乘以 Time.deltaTime。这是因为 FixedUpdate 是在一个可靠的计时器上调用的,与帧速率无关。

    您可以阅读this article 以获得更好的解释,您也可以阅读official documentation

    【讨论】:

    • 这是相反的 AFAIK:您需要在 FixedUpdate 中执行刚体更新。 In a script, the FixedUpdate function is recommended as the place to apply forces and change Rigidbody settings (as opposed to Update, which is used for most other frame update tasks)docs.unity3d.com/ScriptReference/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多