[SOLVED] How do I know when Vector3.SmoothDamp is done moving?

I am trying to make my object float up and then down in a loop .

I use Vector3.SmoothDamp to make it go in the up but I do not seem to be able to find out when it has reached its location.
I use this code to check if it has reached it location but it only log the “0” at start and not when it has stoped moving

if (velocity.y == 0 ) {
            Debug.Log("0");
            moveToYPosition = new Vector3(transform.position.x, newAltitude, transform.position.z);
        }
        transform.position = Vector3.SmoothDamp(transform.position, moveToYPosition, ref velocity, 0.3f, 1.0f);

I have also tried Vector3.zero, but to no success.

So how do I know when Vector3.SmoothDamp has reached it location so I can move the object towards another new location with Vector3.SmoothDamp?

If transform.position == moveToYPosition within some error range. You can rely on Unity’s error factor and just use:

if (transform.position == moveToYPosition)

or you can invent your own standard of “close enough”

Vector3 diff = transform.position-moveToYPosition;
// we will use sqrMagnitude to avoid costly square roots
// so if we need them to be within .01 of each other,
// we check against .0001 (.01*.01)
if (diff.sqrMagnitude < .0001)
    // code for clamp being done
1 Like

Thanks! Now it works :slight_smile:

This is my code “just in case it helps anyone else” :slight_smile: :

       currentTerrainFloor = terrain.SampleHeight(new Vector3(transform.position.x, 0 , transform.position.z));
        hoverAltitudeMin = currentTerrainFloor + hoverFloor;
        hoverAltitudeMax = currentTerrainFloor + hoverCeiling;
        diff = transform.position - moveToYPosition;
        if (diff.sqrMagnitude < .00001f) {
            directionUp = !directionUp;
        }
        if (directionUp) {
            moveToYPosition = new Vector3(transform.position.x, hoverAltitudeMin, transform.position.z);
        } else {
            moveToYPosition = new Vector3(transform.position.x, hoverAltitudeMax, transform.position.z);
        }
        transform.position = Vector3.SmoothDamp(transform.position, moveToYPosition, ref velocity, smoothTime, maxSpeed);