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
If your angle is measured clockwise from (1,0), you can modify the function call like this:
example