Jack
Jack

Reputation: 3415

Get X,Y coordinates from Angle & Distance ( Incorrect values using Math.cos() & Math.sin() )

I've read all accepted answers on this topic and repeated exactly the logic used in them but my results seem to be skewed and 'random'.

I have correctly collected the X,Y and degrees from the center object as shown here:

console.log('deg' + degrees + ' - ' + 'x' + parseInt(x) + ', y' + parseInt(y));

enter image description here Note: The X,Y grid spans much further out of the viewport that is shown. Technically the grid is unlimited in size. We are in our own specific X,Y coordinate in this grid space.

Now I want to calculate an X,Y coordinate that is 1000 pixels away from the click position. Here is an example of what I'm trying to achieve:

enter image description here

The logic I found elsewhere should be as simple as such:

x = 1000 * Math.cos(degrees);
y = 1000 * Math.sin(degrees);
console.log('deg' + degrees + ' - ' + 'x' + parseInt(x) + ', y' + parseInt(y));

The result is as such:

enter image description here

The issue: Clearly in the image above, the X,Y coordinates are way off to what I should be expecting. They are much too low and change too often to random numbers.

The grid for this layout is as shown below:

enter image description here

Note: The X axis goes positive to the left. Is this the underlying issue or is it my original logic that is wrong?

Thank you for considering my question


I've tried the suggested code. Here are my results.

Result from @MBo's now old answer:

new_x = 1000 * Math.cos(degrees * Math.PI / 180);
new_y = 1000 * Math.sin(degrees * Math.PI / 180);

enter image description here

The results look a lot cleaner and less 'random' however the end X,Y go in the incorrect direction and distance

Upvotes: 2

Views: 2664

Answers (1)

MBo
MBo

Reputation: 80325

and change too often

Trigonometric functions work with radians rather than degrees, so calculate arguments like this:

 Math.cos(degrees * Math.PI / 180);
 Math.sin(degrees * Math.PI / 180);

To make rotation around some point, add these values to its coordinates

 x = center_object_x + Math.cos(degrees * Math.PI / 180);
 y = center_object_y + Math.sin(degrees * Math.PI / 180);

Upvotes: 4

Related Questions