Page 1 of 1

How to determine compass direction between two points?

Posted: 13 Jan 2012, 16:05
by aubergine
In the AI I'm making, I want the AI to build anti-aircraft defences closer the enemy, but have artillery a bit further away from the enemy (eg. behind shorter-range defences, sensors, etc).

At a later point, assuming the JS API allows interaction with the in-game chat system, I'd also want the AI to relay information to human players using chat.

So, if I have point A (x1,y1) and point B (x2,y2), I want to get a compass direction from the perspective of point A as to where point B is, something like this:

getCompassDirection(x1,y1,x2,y2)

And the return value would be in degrees from north or, perhaps more eloquently, N, NE, E, SE, S, SW, W, NW. Problem is that it's baking my brain trying to find an elegant way of achieving this.

I'd also want a "clock direction" version of that, based on the player's map orientation - eg. "Base under attack at 6 o'clock" - that's also baking my brain. (and there's no JS API method yet to work out what map orientation a given player is using)

Any ideas?

Re: How to determine compass direction between two points?

Posted: 13 Jan 2012, 16:19
by Cyp
Don't know about in Javascript, but something like atan2(x2 - x1, y2 - y1) gives the angle (where 0 = S, and π/2 = E, ±π = N, -π/2 = W).

Re: How to determine compass direction between two points?

Posted: 13 Jan 2012, 16:24
by aubergine
JS has atan2 on the Math object: http://www.w3schools.com/jsref/jsref_obj_math.asp

I'm crap at math - using return value from atan2 (in radians), how would I convert that in to degrees with 0º being North?

Re: How to determine compass direction between two points?

Posted: 13 Jan 2012, 16:29
by JDW
aubergine wrote:JS has atan2 on the Math object: http://www.w3schools.com/jsref/jsref_obj_math.asp

I'm crap at math - using return value from atan2 (in radians), how would I convert that in to degrees with 0º being North?
Is this what you're looking for? --> http://www.teacherschoice.com.au/maths_ ... angles.htm

Re: How to determine compass direction between two points?

Posted: 13 Jan 2012, 16:35
by aubergine
Awesome - thanks!