在 Unity 中使用数学移动精灵
Moving a sprite using math in Unity
我目前正在 Unity 中制作游戏,其中角色从屏幕顶部的随机 x 位置向屏幕底部的一个点移动。因为他们必须保持恒定的速度(后来可能能够以特定的模式移动),我不能为此使用 Vector3.Lerp
。
相反,我尝试使用一些简单的数学。 StaticInfo.instance.GetPlayerPosition()
是目标位置。该代码发生在角色的 FixedUpdate() 中。
float aVal = (myTransform.localPosition.y - StaticInfo.instance.GetPlayerPosition().y) /
(myTransform.localPosition.x - StaticInfo.instance.GetPlayerPosition().x);
float degrees = Mathf.Atan(aVal) * Mathf.Rad2Deg;
Vector3 newPos = new Vector3(myTransform.localPosition.x - (distance * speed * Mathf.Cos(degrees)),
myTransform.localPosition.y - (distance * speed * Mathf.Sin(degrees)),
1);
myTransform.localPosition = newPos;
我的问题是当创建这些角色时(从预制件实例化),它们会在向所需方向移动之前形成一个 180 度的小循环。在那之后,他们完全按照需要移动。
使用数学是最好的解决方案吗?如果是,为什么它在初始化时会出现奇怪的漂移?
对于您要实现的目标,这可能是一个更简单的解决方案:
Vector3 moveDirection = (StaticInfo.instance.GetPlayerPosition() - myTransform.localPosition).normalized;
Vector3 newPos = myTransform.localPosition + moveDirection * distance * speed;
myTransform.localPosition = newPos;
如果你想让物体指向运动的方向,你可以这样做:
myTransform.rotation = Quaternion.Euler(0, 0, Mathf.atan2(moveDirection.y, moveDirection.x)*Mathf.Rad2Deg - 90); // may not need to offset by 90 degrees here;
我目前正在 Unity 中制作游戏,其中角色从屏幕顶部的随机 x 位置向屏幕底部的一个点移动。因为他们必须保持恒定的速度(后来可能能够以特定的模式移动),我不能为此使用 Vector3.Lerp
。
相反,我尝试使用一些简单的数学。 StaticInfo.instance.GetPlayerPosition()
是目标位置。该代码发生在角色的 FixedUpdate() 中。
float aVal = (myTransform.localPosition.y - StaticInfo.instance.GetPlayerPosition().y) /
(myTransform.localPosition.x - StaticInfo.instance.GetPlayerPosition().x);
float degrees = Mathf.Atan(aVal) * Mathf.Rad2Deg;
Vector3 newPos = new Vector3(myTransform.localPosition.x - (distance * speed * Mathf.Cos(degrees)),
myTransform.localPosition.y - (distance * speed * Mathf.Sin(degrees)),
1);
myTransform.localPosition = newPos;
我的问题是当创建这些角色时(从预制件实例化),它们会在向所需方向移动之前形成一个 180 度的小循环。在那之后,他们完全按照需要移动。
使用数学是最好的解决方案吗?如果是,为什么它在初始化时会出现奇怪的漂移?
对于您要实现的目标,这可能是一个更简单的解决方案:
Vector3 moveDirection = (StaticInfo.instance.GetPlayerPosition() - myTransform.localPosition).normalized;
Vector3 newPos = myTransform.localPosition + moveDirection * distance * speed;
myTransform.localPosition = newPos;
如果你想让物体指向运动的方向,你可以这样做:
myTransform.rotation = Quaternion.Euler(0, 0, Mathf.atan2(moveDirection.y, moveDirection.x)*Mathf.Rad2Deg - 90); // may not need to offset by 90 degrees here;