![](/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.