Nicholas Mueller
Nicholas Mueller

Reputation: 512

Calculate coordinate on a line knowing the start, end, and length of the line?

I'm developing a 2d game in JS and stuck on a trigonometry problem.

Problem: Player shoots a target. The shot is blocked by an obstacle. The obstacle is between the player and the target. I need to figure out the coordinates of this obstacle.

I have 3 pieces of information:

  1. starting coordinate of shot (x1,y1)
  2. ending coordinate of shot (x2, y2)
  3. distance between the starting coordinate and the obstacle

How do I figure out the (x,y) of the obstacle in the way of the shot?

Bonus points: An efficient solution in Javascript.

Picture for reference.

trig-problem

Upvotes: 0

Views: 127

Answers (1)

gog
gog

Reputation: 11347

           E 
           *
          /|
         / |
     O  /  |
       *   |
      /|   |
     / |   |
    /  |   |
 S *---*---*
       P   Q
       
       

SQ = x2 - x1
EQ = y2 - y1


SE = sqrt(SQ^2 + EQ^2)

SO = known

SP:SQ = SO:SE  => SP = SO:SE * SQ 
OP:EQ = SO:SE  => OP = SO:SE * EQ 

Upvotes: 1

Related Questions