Jeremy Ben
Jeremy Ben

Reputation: 11

Get the angle degrees from 2 points on a grid

I have a grid for a flat, 2D map which is a bit different from usual. The top left point is 0,0 and bottom right is 1000,1000. I have 2 points on this map, an origin/anchor point and a destination.

I am looking to figure out the degrees (in javascript) from the origin to the destination. I have looked through many answers and they all don't produce the correct result.

function getAngle(origin_x, origin_y, destination_x, destination_y) {
var newx = destination_x - origin_x;
var newy = destination_y - origin_y;
var theta = Math.atan2(-newy, newx);
if (theta < 0) {
theta += 2 * Math.PI;
}
theta *= 180 / Math.PI;
return theta;
}

This is what I have so far but it doesn't produce the right angle.

Image of the problem

Thankyou very much in advance!

Upvotes: 0

Views: 873

Answers (1)

Kris
Kris

Reputation: 3361

image from mdn Math.atan2 doc

It will give the angle relative to the x-axis, not the y-axis. To convert all you would do is

var newAngle = 90 - theta;

Upvotes: 1

Related Questions