如何创建速度从点A移到点B的线渲染器?
public GameObject gameObject1; // Reference to the first GameObject
public GameObject gameObject2; // Reference to the second GameObject
private LineRenderer line; // Line Renderer
// Use this for initialization
void Start () {
// Add a Line Renderer to the GameObject
line = GetComponent<LineRenderer>();
// Set the width of the Line Renderer
line.SetWidth(0.0012F, 0.0012F);
}
// Update is called once per frame
void Update () {
line.SetPosition(0, new Vector3(gameObject1.transform.position.x,gameObject1.transform.position.y,gameObject1.transform.position.z));
line.SetPosition(1, new Vector3(gameObject2.transform.position.x,gameObject2.transform.position.y,gameObject2.transform.position.z));
}
答案 0 :(得分:1)
我宁愿使用Coroutine,例如(假设两个对象同时不改变位置)
// in seconds
public float duration = 1;
private bool isDoingLine;
private void Start()
{
// Add a Line Renderer to the GameObject
line = GetComponent<LineRenderer>();
// Set the width of the Line Renderer
line.SetWidth(0.0012F, 0.0012F);
line.positionCount = 2;
line.SetPosition(0, gameObject1.transform.position);
line.SetPosition(1, gameObject1.transform.position);
DoLine();
}
public void DoLine()
{
if(!isDoingLine) StartCoroutine(LineRoutine());
}
IEnumerator LineRoutine()
{
isDoingLine = true;
line.SetPosition(0, gameObject1.transform.position);
var timePassed = 0f;
while(timePassed < duration)
{
var factor = timePassed / duration;
// optionally add ease-in ease-out
//factor = Mathf.SmoothStep(0, 1, factor);
line.SetPosition(1, Vector3.Lerp(gameObject1.transform.position, gameObject2.transform.position, factor));
timePassed += Mathf.Min(Time.deltaTime, duration - timePassed);
yield return null;
}
// when done just in case set the final position fix
line.SetPosition(1, gameObject2.transform.position);
isDoingLine = false;
}
使用Vector3.Lerp
在两个位置之间进行插值。
这里真的不需要btw通过new Vector3
。 Vector3
是struct
,因此任何赋值或参数传递都始终使用副本。