【问题标题】:Moving a sprite using math in Unity在 Unity 中使用数学移动精灵
【发布时间】:2017-12-20 16:40:05
【问题描述】:

我目前正在 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 度循环。之后,他们完全按照自己的意愿移动。

使用数学是最好的解决方案吗?如果是,为什么它在初始化时会出现奇怪的漂移?

【问题讨论】:

  • 尝试使用 Atan2(y,x)

标签: c# unity3d game-physics


【解决方案1】:

这可能是您想要实现的更简单的解决方案:

    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;

【讨论】:

  • moveDirection 需要标准化。
  • 现在您需要向前变换方向始终面向 moveDirection。这就是他的问题所在。不过,这对于运动部分来说更简单。
  • 工作就像一个魅力。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 2023-03-15
  • 2015-05-20
  • 2018-05-27
相关资源
最近更新 更多