我试图在 2 个公共位置之间移动游戏对象(不停):
我有这个代码:
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMinima, 0, 0), velocity * Time.deltaTime);
if(transform.position.x==distanciaMinima)
{
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMaxima, 0, 0), velocity * Time.deltaTime);
}
else if(transform.position.x == distanciaMaxima)
{
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMinima, 0, 0), velocity * Time.deltaTime);
}
但是当它在“DistanciaMinima”中时,它就在那里。(我认为每次它开始向 distanMaxima 移动时,distanciaMinima 的代码都会执行。)
任何解决方案
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMinima, 0, 0), velocity * Time.deltaTime);
if(transform.position.x==distanciaMinima)
{
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMaxima, 0, 0), velocity * Time.deltaTime);
}
else if(transform.position.x == distanciaMaxima)
{
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMinima, 0, 0), velocity * Time.deltaTime);
}
我认为最简单的方法是结合
Mathf.PingPong
和Vector3.Lerp
在下面的代码中,
Mathf.PingPong
将返回一个值,该值将在值 0 和长度(在本例中为 1)之间递增和递减。
这与
Vector3.Lerp
结合将使GameObject不断地从positionA
移动到positionB
(当插值为1时到达),然后从positionB
向positionA
移动(当插值为0时到达),并且等等。
void Update()
{
float interpolant = Mathf.PingPong(Time.time * speed, 1);
transform.position = Vector3.Lerp(positionA, positionB, interpolant);
}
谢谢,它也可以使用 bool 变量“bool movingTowardsMinima=true;” :
if (movingTowardsMinima) {
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMinima, 0, 0), velocity * Time.deltaTime);
if (transform.position.x == distanciaMinima)
{
StartCoroutine(StopForTime());
movingTowardsMinima = false;
}
}
else
{
transform.position = Vector3.MoveTowards(transform.position, new Vector3(distanciaMaxima, 0, 0), velocity * Time.deltaTime);
if (transform.position.x == distanciaMaxima)
{
StartCoroutine(StopForTime());
movingTowardsMinima = true;
}
}