![](/img/trans.png)
[英]What is the best way to move game objects, smoothly rather than teleporting it?
[英]Best way to move my Gameobject smoothly?
尝试平滑移动Gameobject时遇到问题 。
我每秒通过TCP协议收到一个位置,我的游戏对象必须移动到该位置。 所以我有我的起始位置 , 终点位置 ,我可以计算两个位置之间的距离 ,我知道我的游戏对象必须以恒定的速度移动到我的终点1秒 。
我尝试了3个解决方案: Learp , MoveToward和SmoothDamp ,但是它们都不起作用,我的Gameobject每次每次都从A点传送到B点。
这是我在代码中尝试的内容( 字典中引用了 我的Gameobject , 我的Gameobject是planes ):
// 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);
该代码是在我的Update中以这种方式调用的函数:
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;
}
}
}
}
最好使用补间引擎,例如http://dotween.demigiant.com/ 。
如果您安装Dotween,则只需使用
transform.DOMove(new vector3(1 ,0 , 1) , duration);
您也可以为补间设置缓动。 或使用不完整功能;
transform.DOMove(new vector3(1 ,0 , 1) , duration)
.SetEase(Ease.OutCubic)
.OnCompelete(() => { shouldClose = true; });
我必须说,您对这三个功能的理解完全错误。 应该在多个更新中调用它们,而不仅仅是一次。
在这种情况下,我建议MoveTowards
。 因为SmoothDamp
不能以恒定的速度移动对象,并且要使用Lerp
,您需要计算两点之间的比率(请注意,如果在每次固定更新时将量添加到t参数中,都可以不断移动对象) 。
这是我为您的游戏对象的MonoBehaviour编写的代码段
const float moveTime = 1;
Vector3 target, step;
void Update () {
transform.position = Vector3.MoveTowards(transform.position, target,
step / moveTime * Time.deltaTime);
}
// Call this method to set the new target (the currently received position from network)
public void SetTarget (Vector3 positon) {
target = positon;
step = Vector3.Distance(transform.position, target);
}
Time.deltaTime
是Time.deltaTime
更新之间的间隔(其中调用了Update ()
函数)
我建议以下内容:
在“ ObjectMover”的Update方法中,使用lerp或使用step / moveTime * Time.deltaTime计算自己的步进,以移至所需的新位置,并仅根据所需的外观调整速度。
从您的“主要”脚本中执行ObjectIWantToMove.GetComponent()。MoveToNewPos(newPos); 它将平稳地移动到那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.