首先,你需要知道图像的局部方向应该是指向运动的方向。这取决于您的设置,并且该问题不包含足够的信息来准确了解。可能是Vector3.up 或Vector3.right。当然,世界方向是从速度得知的。
Vector3 worldDirectionToPointForward = rb2d.velocity.normalized;
Vector3 localDirectionToPointForward = Vector3.right;
然后,您希望围绕 z 轴旋转精灵,以使局部方向指向该方向。您可以使用transform.TransformDirection 找到球当前“指向”的方向,然后使用Vector3.SignedAngle 计算角度:
Vector3 currentWorldForwardDirection = transform.TransformDirection(
localDirectionToPointForward);
float angleDiff = Vector3.SignedAngle(currentWorldForwardDirection,
worldDirectionToPointForward, Vector3.forward);
然后,使用 transform.Rotate 将其绕 z 轴旋转该量。
transform.Rotate(Vector3.forward, angleDiff);
我会在与墙壁发生碰撞后执行此操作。另一种方法是将其放在LateUpdate 中,尽管这可能会干扰其他单一行为中LateUpdate 中发生的其他事情。但是,LateUpdate 方法最容易演示,因此我将在此处演示:
void LateUpdate()
{
Vector3 worldDirectionToPointForward = rb2d.velocity.normalized;
Vector3 localDirectionToPointForward = Vector3.right;
Vector3 currentWorldForwardDirection = transform.TransformDirection(
localDirectionToPointForward);
float angleDiff = Vector3.SignedAngle(currentWorldForwardDirection,
worldDirectionToPointForward, Vector3.forward);
transform.Rotate(Vector3.forward, angleDiff, Space.World);
}