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

Thanks in advance!

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

Started by seesig, Dec 08 2011 09:46 PM

5 replies to this topic

### #1

Posted 08 December 2011 - 09:46 PM

### #2

Posted 08 December 2011 - 09:47 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.

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 - 09:48 PM.**

### #3

Posted 08 December 2011 - 09:49 PM

Thank you very much!

### #4

Posted 08 December 2011 - 09:52 PM

And the other way:

speed=sqrt(sqr(hspeed)+sqr(vspeed)) direction=arctan2(vspeed,hspeed)*180/pi

YoYoGames | Youtube | Twitter | TheSnidr.com

### #5

Posted 10 December 2011 - 03:21 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...

### #6

Posted 10 December 2011 - 03:22 AM

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

#### 0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users