Check if object is moving towards a point

Greetings! I’m looking to find a solution to check if an object is moving towards a vector3 position (or another object’s position). Basically if the distance is decreasing, return true, else if it’s increasing, return false.

Thanks to Elthen for giving the Vector3.distance idea.

Put this code at the top:

public float dist;

And this function at the bottom:

public bool CheckDirection () {
    float distTemp = Vector3.Distance(destination.position, transform.position);
    if (distTemp < dist) {
        dist = distTemp;
        return true;
    } else if (distTemp > dist) { // rigorous checking
        dist = distTemp;
        return false;
    }
}

Make sure the function is being called constantly (I am assuming it will be)

Basically it checks if the distance last frame was further or closer than the distance this frame, and then returns the desired value.

Tell me if it doesn’t work and I can see what I can change.

Sorry if you wanted it in Java, but hopefully you get the main idea of the code.

Hmmm not sure if this would help; anyway, you could keep track of the distance by using Vector3.Distance() inside an Update() to check the distance between two Vector, like so:

    if (Vector3.Distance(destination.position, transform.position) > 0.5f)
    {
    //do something
    }

See: Unity - Scripting API: Vector3.Distance