0

I want to move a cube A to another cube B using Lerp, but only if the distance between them is greater than 2.0f. But since Lerp is applied in multiple Update() frames, in the next Update() the distance between the two cubes is 1.9 for example, and the code doesn´t enter in the if statment and the cube A just stops there.

How could I move the cube A to cube B?

void Start()
{
        startPos = transform.position;
}

void Update()
{
        float distance = Vector3.Distance(transform.position, nextStepPos.position);

        if (distance > 2.0f)
        {
            transform.position = Vector3.Lerp(transform.position, nextStepPos.position, speed * Time.deltaTime);
        }
         else
        {   
            transform.position = startPos;
        }
}
kannaMain
  • 11
  • 3
  • Did you find an answer to this question? If mine was helpful, please consider [accepting it](https://meta.stackexchange.com/a/5235/405359) to give me some reputation points and help others browsing the search panel that there is a helpful answer here. – Ruzihm Nov 16 '21 at 22:25

1 Answers1

1

I would use Vector3.MoveTowards instead of Lerp and use a Coroutine for this:

[SerializeField] Transform nextStepPos;
Coroutine moveToOtherCoroutine;
float moveSpeed = 1f; // world units per second

void Start()
{
    moveToOtherCoroutine = null;
}

void Update()
{
    if (distance > 2.0f)
    {
        if (moveToOtherCoroutine == null)
            moveToOtherCoroutine = StartCoroutine(DoMoveToOther());
    }
}

IEnumerator DoMovetoOther()
{
    while (true)
    {
        Vector3 newPos = Vector3.MoveTowards(transform.position, nextStepPos.position, 
                Time.deltaTime * moveSpeed);
        transform.position = newPos;
        if (newPos == nextStepPos.position) 
        {
            break;
        } 
        yield return null;
    } 
    // If you want to allow moving to the cube on distance > 2.0f again
    // moveToOtherCoroutine = null;

    // Stuff that should happen when reach next step should happen here
}
Ruzihm
  • 19,749
  • 5
  • 36
  • 48