来回移动游戏对象 [英] Move GameObject back and forth

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

问题描述

我有一个对象,我想向上移动到 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 个 Lerp:

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 获取01 然后将该值传递给 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 将自动返回值会在 01 之间来回移动.阅读链接的文档了解更多信息.

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);
}

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

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