简体   繁体   English

来回移动GameObject

[英]Move GameObject back and forth

I got an Object that I want to move up to Point A and when it reaches Point A it should move to Point B. When it reaches Point B it should move back to Point A. 我有一个要向上移动到点A的对象,当它到达点A时应移动到点B。当它到达点B时应移动回到点A。

I thought I could use Vector3.Lerp for this 我以为我可以使用Vector3.Lerp

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

But how can i move back then? 但是那我该怎么回去呢? Is there an elegant way to archieve this? 是否有一种优雅的方式来存档? Obviously I would need 2 Lerps like this way: 显然,我需要这样的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
}

Could someone help me out? 有人可以帮我吗?

There are many ways to do this but Mathf.PingPong is the easiest and the simplest way to accomplish this. 有很多方法可以做到这一点,但是Mathf.PingPong是实现此目的最简单的方法。 Use Mathf.PingPong to get number between 0 and 1 then pass that value to Vector3.Lerp . 使用Mathf.PingPong获取01之间的数字,然后将该值传递给Vector3.Lerp That's it. 而已。

Mathf.PingPong will automatically return value will that will move back and forth between 0 and 1 . Mathf.PingPong将自动返回将在01之间来回移动的值will。 Read the linked documentation for more info. 阅读链接的文档以获取更多信息。

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