I want to know if the rb2D is moving away or towards the other position. Is there a formula to determine this?
1 Answer
\$\begingroup\$
\$\endgroup\$
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?