Raycast 或计时或滞后?

Raycast or timing or lag?

所以我运行正在对教程中的光线投射物理处理程序进行测试。每次模拟时,我都会从相同的高度放下一个方块,目的是让方块以一种平滑的运动落在平坦表面的顶部。目前,我的光线投射通过皮肤宽度从盒子底部投射出来,光线长度按 velocity.y 缩放,如下所示:

rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x);
//Sends out the ray at its respective spot an length

RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);
Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);

//If the ray hits, make velocity = distance to the hit distance - skin width
//Also reset the rayLength for edge height discrepencies
if (hit)
{
    //Reports the very first hit.distance and velocity.y at the first hit
    if (!temp && hit.distance != 0)
    {
        Debug.Log(hit.distance);
        Debug.Log(velocity.y);
        temp = true;
    }

    velocity.y = (hit.distance - skinWidth) * directionY;
    rayLength = hit.distance;
}

我的问题是,当我 运行 一遍又一遍地进行这种模拟时,大约有一半的时间,当方块与平坦表面碰撞时,它会在表面上方产生这个初始 "stopping force" 一点,并且然后块上的重力重新启动并将其直接拉到表面上。

所以基本上,有时它会在比其他时间更远的距离上感应到碰撞,迫使它过早地在半空中停下来。我已经通过观察 hit.distancevelocity.y 上的 Debug.Log 来绘制它。这种不利影响发生的时间,hit.distance0.1 以上,velocity.y-9.56 左右,而有利的时间 hit.distance 在某处0.1 下方,velocity.y-9.67

当我根本没有改变系统时,是什么导致了模拟高度和数字的差异?它是在编辑器中滞后还是需要考虑的问题?它会出现在移动应用程序上吗?

感谢您的帮助。

正如评论所证实的那样,我的怀疑是正确的:

您是 运行 此代码 Update() 而不是 FixedUpdate(),因此它与物理引擎不同步。差异(在子更新间隔内)导致更新循环的代码提前执行,施加了太大的力,所以到物理模拟时 运行(在 FixedUpdate 的时间表上)对象仍然太高并且重力再来一次。

唯一的解决办法是将您的代码移至 FixedUpdate()