Search code examples
unity-game-enginemathartificial-intelligencegame-physicsvectormath

Point of intersection between two vectors when the direction of one vector is not known


Problem: I have two vectors. I know the starting point of one vector, its direction, its magnitude. I know the starting point of the other vector and its magnitude. I need to find the direction of second vector as well as the position of intersection.

   Vector A:                        Vector B:

Position = Known                   Position = Known  
Direction= Known                   Direction= UNKNOWN
Magnitude= Known                   Magnitude= Known

To Find: Point of intersection.

Is it possible to find the point of intersection, with the given parameters? If so then how?

Application: I want to find the position where a player would be found based on the velocity he is moving, and shoot a bullet at him at the moment he would be found, taking into account the time taken for the bullet to reach that virtual target position.


Solution

  • Following on from the comments I'm going to take a leap here and answer your ultimate question directly.

    Say the player is, at the initial time, at a point p and travelling with velocity v; your gun is at position q and shoots a bullet in any direction at speed s:

    enter image description here

    The length of OP is vΔt and that of Q sΔt. The angle a is given by the dot product:

    enter image description here

    We can then use the cosine rule to solve for Δt:

    enter image description here

    Written in this form, we can easily see that it is a quadratic equation, and thus directly solve for Δt using the Quadratic formula:

    enter image description here

    There are a few cases we need to consider here:

    • v < s: need to take the positive root only as otherwise we would get negative time.
    • v > s and dot(PQ, s) < 0: the bullet will never catch the player.
    • v > s and dot(PQ, s) > 0: take the negative root this time, as the positive root is for a backwards travelling player (longer time; this is also the case presented in the diagram above).

    Having the correct value for Δt from above will then enable us to find the intersection point o, and therefore the intended direction d:

    enter image description here

    Note that d is not normalized. Also, this solution works for 3D too, unlike an approach with angles.