How to find angle

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
schme16
Party member
Posts: 127
Joined: Thu Oct 02, 2008 2:46 am

How to find angle

Post by schme16 »

I appologise for what could be a really silly question, but I havn't found an answer that made sense to me, yet.

What I'm after is how to find the angle (in degrees or radians) between two co-ordinate points

eg: what is the angle between x1,y1 and x2,y2

any and all help greatly appreciated!

Cheers,
My Development Diary - http://shanegadsby.info
User avatar
bmelts
Party member
Posts: 380
Joined: Fri Jan 30, 2009 3:16 am
Location: Wiscönsin
Contact:

Re: How to find angle

Post by bmelts »

http://en.wikipedia.org/wiki/Atan2

Conveniently located in Lua's math library.
User avatar
BlackBulletIV
Inner party member
Posts: 1261
Joined: Wed Dec 29, 2010 8:19 pm
Location: Queensland, Australia
Contact:

Re: How to find angle

Post by BlackBulletIV »

I took this code from FlashPunk:

Code: Select all

function math.angle(x1, y1, x2, y2)
    local a = math.deg(math.atan2(y2 - y1, x2 - x1))
    if a < 0 then
        return a + 360
    else
        return a
    end
end
User avatar
schme16
Party member
Posts: 127
Joined: Thu Oct 02, 2008 2:46 am

Re: How to find angle

Post by schme16 »

Thanks heaps guys, sorry I fail at math so hard :P
My Development Diary - http://shanegadsby.info
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: How to find angle

Post by bartbes »

I prefer radians, as, well, all functions are using radians, so degrees are only useful when you are outputting it, also, if you replace the if by the modulus operator you get this:

Code: Select all

function math.angle(x1, y1, x2, y2)
    return math.deg(math.atan2(y2-y1, x2-x1))%360
end
Which is.. perhaps a bit nicer. On yet another note, I dislike putting your own functions in the std libs, but I guess, as most of the things I mentioned, it's a matter of preference.
User avatar
BlackBulletIV
Inner party member
Posts: 1261
Joined: Wed Dec 29, 2010 8:19 pm
Location: Queensland, Australia
Contact:

Re: How to find angle

Post by BlackBulletIV »

bartbes wrote:

Code: Select all

function math.angle(x1, y1, x2, y2)
    return math.deg(math.atan2(y2-y1, x2-x1))%360
end
Wow, that's really clever. Modulo is a pretty awesome operator.
User avatar
schme16
Party member
Posts: 127
Joined: Thu Oct 02, 2008 2:46 am

Re: How to find angle

Post by schme16 »

heck yes it is, thanks heaps bartbes
My Development Diary - http://shanegadsby.info
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 94 guests