Measuring indirect velocity.magnitude

Hi Guys,

Is there a way to measure the speed one object is heading towards another when it is not moving in a directly towards the object (so it does not equal velocity.magnitude as it is not heading directly towards that object)?

//Object 1
\/
O -------------------------------->
   \
     \
      \ 
        \
         \
           \
            \
             \
               \
               O <--- //Speed object one is moving to object 2 at any point.
                /\
             //Object 2

It should be the projection of velocity of object 2 onto the unit vector from object 2’s position to object 1’s position, plus the projection of velocity of object 1 onto the same unit vector.

Let V1 and P1 be the velocity and position of object 1, respectively.
Let V2 and P2 be the velocity and position of object 2, respectively.

d = (P2 - P1) / |P2 - P1|
V12 = (V1 · d + V2 · d) * d

Where d is the unit vector in the direction of object 1 to object 2, and V12 is the velocity of object 1 in the direction of object 2 relative to the velocity of object 2.

C#

// Return the relative velocity of object 1 and object 2 in the direction of 1 to 2.
public static Vector3 RelativeVelocity(Vector3 v1, Vector3 p1, Vector3 v2, Vector3 p2)
{
   Vector3 d = Vector3.Normalize(p2 - p1);
   return (Vector3.Dot(v1, d) + Vector3.Dot(v2, d)) * d;
}

Incidentally, if you just want a signed speed rather than a velocity vector, the relative speed of object 1 to object 2, which is the signed scalar magnitude of the relative velocity, will be the dot product of vectors d and V12. This also simply works out by not multiplying the projected velocity magnitudes by the direction vector, and you can rewrite the function this way…

// Return the signed relative speed of object 1 and object 2 in the direction of 1 to 2.
public static float RelativeSpeed(Vector3 v1, Vector3 p1, Vector3 v2, Vector3 p2)
{
   Vector3 d = Vector3.Normalize(p2 - p1);
   return (Vector3.Dot(v1, d) + Vector3.Dot(v2, d));
}

This function should return a positive speed if the objects are approaching each other, the speed should be zero if the distance between them is not changing at all, and it should be a negative speed of the objects are retreating. Hopefully that is clear.

This code is untested, but should work. If you have any problems, I will revisit it.