簡體   English   中英

來回移動GameObject

[英]Move GameObject back and forth

我有一個要向上移動到點A的對象,當它到達點A時應移動到點B。當它到達點B時應移動回到點A。

我以為我可以使用Vector3.Lerp

void Update()
{
  transform.position = Vector3.Lerp(pointA, pointB, speed * Time.deltaTime);
}

但是那我該怎么回去呢? 是否有一種優雅的方式來存檔? 顯然,我需要這樣的2個Lerps:

void Update()
{
  transform.position = Vector3.Lerp(pointA, pointB, speed * Time.deltaTime); // Move up
  transform.position = Vector3.Lerp(pointB, pointA, speed * Time.deltaTime); // Move down
}

有人可以幫我嗎?

有很多方法可以做到這一點,但是Mathf.PingPong是實現此目的最簡單的方法。 使用Mathf.PingPong獲取01之間的數字,然后將該值傳遞給Vector3.Lerp 而已。

Mathf.PingPong將自動返回將在01之間來回移動的值will。 閱讀鏈接的文檔以獲取更多信息。

public float speed = 1.19f;
Vector3 pointA;
Vector3 pointB;

void Start()
{
    pointA = new Vector3(0, 0, 0);
    pointB = new Vector3(5, 0, 0);
}

void Update()
{
    //PingPong between 0 and 1
    float time = Mathf.PingPong(Time.time * speed, 1);
    transform.position = Vector3.Lerp(pointA, pointB, time);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM