Search code examples
javascriptmathcoordinatesangle

How can we calculate coords of the end point if we know start point, distance and angle?


We know the start point, the angle and the distance between start and end points.

let x1 = 500;
let y1 = 500;
let angle = 45;
let distance = 100;

How can we calculate the coordinates of the end point?

enter image description here

It must be some method like Math.atan2...


Solution

  • Using Javascript, given the theta angle, and the length of the hypotenuse, find the opposite and adjacent sides:

    let x1 = y1 = 500, // starting point
      hyp = 100, // hypotenuse
      theta_deg = 45, // theta angle in degrees
      rad = (parseFloat(theta_deg) * Math.PI) / 180, // convert deg to radians
      
      // opp = hyp * sin(θ)
      opp = Math.round((hyp * Math.sin(rad)) * 100) / 100, // opposite side
      
      // adj = √( (hyp * hyp) - (opp * opp) )
      adj = Math.round((Math.sqrt((hyp * hyp) - (opp * opp))) * 100) / 100, // adjacent side
      x2 = x1 + adj, y2 = y1 + opp; // end point
    
    console.log('opposite side:', opp, ' adjacent side:', adj);
    console.log('end point coord. = x2:', x2, ' y2:', y2);

    Note: degrees must be converted to radians before applying to Javascript Math sine methods.

    let deg = 45;
    let rad = (parseFloat(deg) * Math.PI) / 180;
    // 0.7853981633974483