Friday, July 15, 2022
HomeGame Developmentunity - Easy methods to know if a rigidbody2D is shifting away...

unity – Easy methods to know if a rigidbody2D is shifting away or in the direction of one other place?


This can be a easy use of a dot product:

// Returns 1 if the physique is shifting away (distance rising),
// -1 if shifting towards (distance rising),
// and 0 if shifting perpendicular (no change in distance)
float MovementDirection(Rigidbody2D physique, Vector2 place) {
    // Assemble a vector that factors from the reference place to the physique.
    var away = physique.place - place;

    // Examine this route towards the physique's velocity.
    float dot = Vector2.Dot(physique.velocity, away);

    if (Mathf.Roughly(dot, 0)) return 0;    
    return Mathf.Signal(dot);
}

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments