[英]How can I move an object to target more accurate more close to the target and then make the object child of the target?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveNavi : MonoBehaviour
{
public float speed;
private GameObject rig_f_middle;
// Start is called before the first frame update
void Start()
{
rig_f_middle = GameObject.Find("rig_f_middle.02.R");
}
// Update is called once per frame
void Update()
{
if(IKControl.startMovingNAVI == true)
{
Vector3 moveDir = (rig_f_middle.transform.position - transform.position).normalized;
transform.position += moveDir * speed * Time.deltaTime;
}
}
}
這樣做的問題是,即使它非常接近目標,移動的變換也不會停止移動,我希望它停止移動。
我還想讓變換盡可能接近目標,現在它非常接近它但不在它上面。
最后我想在對象到達目標並停止移動時使對象成為目標的子對象。
您可以在更新中引入檢查以測量您離目標轉換有多遠,如下所示:
void Update ( )
{
if ( IKControl.startMovingNAVI == true )
{
var v = rig_f_middle.transform.position - transform.position;
if ( v.magnitude < yourToleranceValue )
{
this.transform.parent = rig_f_middle.transform;
this.enabled = false;
return;
}
Vector3 moveDir = v.normalized;
transform.position += moveDir * speed * Time.deltaTime;
}
}
現在,我個人會采取額外的步驟,只檢查sqrMagnitude
,而不是magnitude
因為計算更輕,尤其是在更新循環中,但也許這是您不需要或不關心的優化。 無論哪種方式,您只需將yourToleranceValue
適當地設置為公共的、可序列化的字段或您的選擇。 然后當兩個變換足夠接近時,它作為這個變換的父級,同時關閉這個組件,因此不再執行檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.