Page 1 of 1

get what angle an object is moving at ?

Posted: Wed Sep 13, 2017 10:28 am
by Vrx8
for example.. i move my mouse to top left corner from the middle of the screen.. then my mouse is moving at 45 degree angle, but how do i get the value ?

Re: get what angle an object is moving at ?

Posted: Wed Sep 13, 2017 11:03 am
by erasio
Generally you would want to have discrete steps with some time in between because of minor inaccuracies and the really small change in position.

The solution is trigonometry!

The formula is:

Code: Select all

angle = math.atan2(dx, dy)
Where dx and dy are the difference between pointA and pointB.

Code: Select all

 
dx = math.abs(x1 - x2)
dy = math.abs(y1 - y2) 
Edit: oh. Minor mistake by me. The angle will be in radians (a number between 0 and 2pi) . If you need degrees you need to translate the angle from radians to degree.

Re: get what angle an object is moving at ?

Posted: Wed Sep 13, 2017 11:29 am
by zorg
And thankfully, lua has functions for that: math.deg and math.rad convert from radians to degrees and vice versa.

Re: get what angle an object is moving at ?

Posted: Wed Sep 13, 2017 1:37 pm
by ivan
Yep, erasio is on the right path except that atan2 accepts the y coordinate first:

Code: Select all

angle = math.atan2(dy, dx)
This is important since in trig you expect an angle of 0 to point East and to increase counter-clockwise
so that both math.pi and -math.pi point West. Therefore 2pi or math.pi*2 or 360 degrees actually points East.
Also, note that atan2 ALWAYS returns a value between -math.pi and math.pi.

To get the "vector" between two points we use:

Code: Select all

dx = x1 - x2
dy = y1 - y2
without the math.abs()

In short the code should be
headingAngle = math.atan2(finalY - initialY, finalX - initialX)

Re: get what angle an object is moving at ?

Posted: Wed Sep 13, 2017 2:09 pm
by Vrx8
erasio wrote: Wed Sep 13, 2017 11:03 am Generally you would want to have discrete steps with some time in between because of minor inaccuracies and the really small change in position.

The solution is trigonometry!

The formula is:

Code: Select all

angle = math.atan2(dx, dy)
Where dx and dy are the difference between pointA and pointB.

Code: Select all

 
dx = math.abs(x1 - x2)
dy = math.abs(y1 - y2) 
Edit: oh. Minor mistake by me. The angle will be in radians (a number between 0 and 2pi) . If you need degrees you need to translate the angle from radians to degree.
thx

Re: get what angle an object is moving at ?

Posted: Wed Sep 13, 2017 2:36 pm
by erasio
Oh man. I really am not at the point where I can do this from the top of my head yet.

Listen to Ivan. Everything he said is absolutely right.

Math.abs would just ignore half of the angles (what the heck was I thinking?) and yes indeed. Y is first for atan2.