javascriptmathvectorsquirrel

Calculate the distance between the players AIM (xyz, pitch, yaw) and the TARGET Vector(xyz)


We have a target, which is somewhere in the level, and a player that can move around and can aim anywhere. Now we want to calculate the distance between the players AIM and the TARGET.

How far off is the players aim from the target? - If this value is close to '0' we know the player is aiming at the target. We want to know this, since we like to calculate how far off the player was, when they fired a shot.

The following info is what we have:

Drawing of the Situation


Solution

  • So you defined the distance as the distance between the target point in the space and the line of aim. Note that you could also define the distance as the angle between the line connecting the player and the target and the line of aim.

    Fortunately this is easy:

    enter image description here

    Point b is the prepandicular projection of the Target to the line aim:

    t = Target - Player
    i = max(a*t/a*a, 0) (so we won't report false distances when the target is behind)
    B = Player + a * i
    distance = dist(B, Target) = len(B - Target)
    

    You can calculate the vector a from pitch and yaw with some formulae like these:

    a_x = cos(pitch) * cos(yaw)
    a_y = sin(pitch)
    a_z = cos(pitch) * sin(yaw)