# The algorithm behind "direction" and "speed"?

5 replies to this topic

### #1 seesig

seesig

GMC Member

• New Member
• 17 posts

Posted 08 December 2011 - 10:00 PM

Currently, I'm attempting to emulate Game Maker's movement system in Java. It currently uses the hspeed and vspeed variables to determine the speed and direction. However, I want to be be able to access these two variables using direction and speed.

Does anyone know how Game Maker converts "direction" and "speed" into "hspeed" and "vspeed"? I'm not asking for any Java code; I'd like it in either GML or plain English, please

• 0

### #2 DanRedux

DanRedux

GMC Member

• GMC Member
• 1404 posts
• Version:GM:Studio

Posted 08 December 2011 - 10:01 PM

hspeed = lengthdir_x( speed, direction )
vspeed = lengthdir_y( speed, direction )

In math terms:

hspeed = cos( degtorad( direction ) ) * speed
vspeed = -sin( degtorad( direction ) ) * speed

In even mathier terms:

hspeed = cos( pi * direction / 180 ) * speed
vspeed = -sin( pi * direction / 180 ) * speed

Any of then will work.

Edited by time4dan, 08 December 2011 - 10:02 PM.

• 0

### #3 seesig

seesig

GMC Member

• New Member
• 17 posts

Posted 08 December 2011 - 10:03 PM

Thank you very much!
• 0

### #4 TheSnidr

TheSnidr

Heavy metal viking dentist

• GMC Elder
• 3345 posts
• Version:GM:Studio

Posted 08 December 2011 - 10:06 PM

And the other way:
speed=sqrt(sqr(hspeed)+sqr(vspeed))
direction=arctan2(vspeed,hspeed)*180/pi

• 0

### #5 seesig

seesig

GMC Member

• New Member
• 17 posts

Posted 10 December 2011 - 03:35 AM

Alright, the algorithm doesn't seem to be working; if the speed is at zero, then common sense would say that the hspeed would be zero. But for some reason, once hspeed hits zero, the hspeed is at 1. I have determined that this is because the cos of zero is 1, hence the hspeed would then be set to 1. This is bad, because if either the speed or the direction is zero(which, in Game Maker, it very commonly is) then the function will return "1". Clearly, this isn't what Game Maker uses...
• 0

### #6 DanRedux

DanRedux

GMC Member

• GMC Member
• 1404 posts
• Version:GM:Studio

Posted 10 December 2011 - 03:36 AM

Not true, because it's being multiplied by speed. If speed truly was 0, the equation would become 0.
• 0