skip to Main Content

I would like to use javascript to locate the x and y coordinate of any point on a Cartesian coordinate system when given an angle between 0 and 2pi and the distance from the origin.

Is there simpler way of writing this function? (in my program angles are measured clockwise from (1,0))

function findPosition(distance, angle){
    let dx, dy;
    if (angle >= 0 && angle <= Math.PI/2){
        dx = distance * Math.cos(angle);
        dy = distance * Math.sin(angle);
    } else if (angle > Math.PI/2 && angle <= Math.PI){
        dx = -distance * Math.cos(angle);
        dy = distance * Math.sin(angle);
    } else if (angle > Math.PI && angle <= 3 * Math.PI / 2){
        dx = -distance * Math.cos(angle);
        dy = -distance * Math.sin(angle);
    } else if (angle > 3* Math.PI/2 && angle <= 2 * Math.PI){
        dx = distance * Math.cos(angle);
        dy = -distance * Math.sin(angle);
    } else {
        console.log("Error: Bad angle");
    }
    return [dx , dy]
}

2

Answers


  1. function findPosition(distance, angle) {
      const dx = distance * Math.cos(angle);
      const dy = distance * Math.sin(angle);
      return [dx, dy];
    }
    

    If your angle is measured clockwise from (1,0), you can modify the function call like this:

    const angle = 2 * Math.PI - desiredAngle;
    const position = findPosition(distance, angle);
    
    Login or Signup to reply.
  2. example

    function findPosition(distance, angle) {
        const cosA = Math.cos(angle);
        const sinA = Math.sin(angle);
        const dx = distance * cosA;
        const dy = distance * sinA;
        return [dx, dy];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search