0
\$\begingroup\$

I want to know if the rb2D is moving away or towards the other position. Is there a formula to determine this?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This is a straightforward use of a dot product:

// Returns 1 if the body is moving away (distance increasing),
// -1 if moving toward (distance increasing),
// and 0 if moving perpendicular (no change in distance)
float MovementDirection(Rigidbody2D body, Vector2 position) {
    // Construct a vector that points from the reference position to the body.
    var away = body.position - position;

    // Compare this direction against the body's velocity.
    float dot = Vector2.Dot(body.velocity, away);

    if (Mathf.Approximately(dot, 0)) return 0;    
    return Mathf.Sign(dot);
}

For more information about how the dot product works, see How do I interpret the dot product of non-normalized vectors?

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .