Search code examples
c++vectorvectormath

vector math - find if object is moving towards or away from a point


I'm not too good with vector math, the closest I came to this was:

sf::Vector2f dir = findObject->m_position - p_object->m_position;
float d = p_object->m_velocity.x * dir.x + p_object->m_velocity.y * dir.y;
if(d > 0) {
      // moving towards
}

where p_object is an object moving towards another object, findObject

but this probably isn't right.


Solution

  • Use dot product.

    bool isMovingTowards(vec2 testPoint, vec2 objectPosition, vec2 objectVelocty) {
        vec2 toPoint = testPoint - objectPosition; //a vector going from your obect to the point
        return dot(toPoint, objectVelocity) > 0;
    }
    

    I'm not sure if you know of dot product, but your code is essentially performing the math to do it. Ie, you're code is almost correct, it could just be a little clearer.