unity3d 在两个位置之间无限移动一个游戏物体

wgeznvg7  于 2023-04-07  发布在  其他
关注(0)|答案(2)|浏览(181)

我正在尝试在两个公共位置之间移动一个游戏对象(没有停止):
我有这个代码:

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”时,它就停在那里了。(我想每次它开始向distanciaMaxima移动时,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);

    }
tjvv9vkg

tjvv9vkg1#

我认为最简单的方法是组合Mathf.PingPongVector3.Lerp
在下面的代码中,Mathf.PingPong将返回一个值,该值将在值0和长度(在本例中为1)之间递增和递减。
这与Vector3.Lerp相结合将使游戏对象从positionApositionB连续移动(当插值为1时到达它),然后从positionBpositionA移动(当插值为0时到达它),等等。

public Vector3 positionA;
public Vector3 positionB;
public float speed = 1.0f;

private void Update()
{
   float interpolant = Mathf.PingPong(Time.time * speed, 1);
   transform.position = Vector3.Lerp(positionA, positionB, interpolant);
}
gg0vcinb

gg0vcinb2#

谢谢,它也可以使用bool变量“bool movingTowardsMinima=true;“……”
public void run(){

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

相关问题