来回移动GameObject [英] Move GameObject back and forth

查看:83
本文介绍了来回移动GameObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要向上移动到点A的对象,当它到达点A时应该移动到点B.当到达点B时它应该移动回到点A.

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.

我认为我可以为此使用Vector3.Lerp

I thought I could use Vector3.Lerp for this

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

那我该如何退回去?是否有一种优雅的方式来存档?显然,我需要像这样的2个Lerps:

But how can i move back then? Is there an elegant way to archieve this? Obviously I would need 2 Lerps like this way:

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 来获取介于 0 1 然后将该值传递给Vector3.Lerp.就是这样.

There are many ways to do this but Mathf.PingPong is the easiest and the simplest way to accomplish this. Use Mathf.PingPong to get number between 0 and 1 then pass that value to Vector3.Lerp. That's it.

Mathf.PingPong 将自动返回将来回移动的值在 0 1 之间.阅读链接的文档以获取更多信息.

Mathf.PingPong will automatically return value will that will move back and forth between 0 and 1. 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);
}

这篇关于来回移动GameObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆