【发布时间】:2016-04-15 03:54:28
【问题描述】:
我在尝试平稳移动游戏对象时遇到问题。
我每秒通过 TCP 协议收到一个位置,我的游戏对象必须移动到该位置。所以我有了我的开始位置,我的结束位置,我可以计算出两个位置之间的距离,我知道我的游戏对象必须移动在 1 秒内匀速到达终点。
我尝试了 3 种解决方案:Learp、MoveToward 和 SmoothDamp,但它们都不起作用,我的游戏对象只是从 A 点传送每次都去B点。
这是我在代码中尝试的内容(我的游戏对象在字典中被引用,我的游戏对象是平面):
// Distance between my 2 points
float step = Vector3.Distance(planeId_Object_Dictionnary[newPlane.Flight].transform.position, new Vector3((float)newPlane.X, (float)newPlane.Afl / (3.2808f * 1852f), (float)newPlane.Y));
//Use of Lerp
//planeId_Object_Dictionnary[newPlane.Flight].transform.position = Vector3.Lerp(planeId_Object_Dictionnary[newPlane.Flight].transform.position, new Vector3((float)newPlane.X, (float)newPlane.Afl / (3.2808f * 1852f), (float)newPlane.Y), step);
//Use of MoveTowards
planeId_Object_Dictionnary[newPlane.Flight].transform.position = Vector3.MoveTowards(planeId_Object_Dictionnary[newPlane.Flight].transform.position, new Vector3((float)newPlane.X, (float)newPlane.Afl / (3.2808f * 1852f), (float)newPlane.Y), step);
//Use of SmoothDamp
//planeId_Object_Dictionnary[newPlane.Flight].transform.position = Vector3.SmoothDamp(planeId_Object_Dictionnary[newPlane.Flight].transform.position, new Vector3((float)newPlane.X, (float)newPlane.Afl / (3.2808f * 1852f), (float)newPlane.Y), ref newPlane.GroundSpeed, 1);
代码是在我的更新中以这种方式调用的函数:
void Update () {
lock (threadLock)
{
// Message receive from my TCP Protocol
while (q_orders.Count > 0)
{
switch (q_orders.Dequeue())
{
case OrderType.trackmovedevent:
aircraftMajInfos(q_args.Dequeue()); // My function to move my Object
break;
}
}
}
}
【问题讨论】:
-
您是在 Update() 或任何其他循环中调用 MoveTowards 吗?
-
是的,我在我的更新中调用它。
-
对 Lerp 和 SmoothDamp 的最后一个参数使用较低的值。 Lerp 的工作方式是获取点 A 和点 B,然后查看最终参数中的值 S 并返回点 C。基本上 S 表示 A 和 B 之间的归一化值,即 S=0 返回 A,S=1 返回 B , S=0.5 返回 A 和 B 之间的中点,依此类推......换句话说,距离(A,C)和距离(B,C)的比率等于 S 和(1 - S)的比率。因此,在您的情况下,制作 S 1 将始终返回目的地点,从而导致“传送”。使该值小于 1。
-
另外,为了使 Lerp 帧速率独立,你可以将 S 值与 Time.deltaTime 相乘。所以以 60fps 播放的人不会比以 30fps 播放的人有更快的过渡。
-
有了这个解决方案,我怎么能确定我会在 1 秒内从 A 点到 B 点?我尝试将第三个参数设置为 0.1*Time.deltaTime,它的移动非常缓慢且不顺畅:(
标签: c# unity3d unityscript unity5