Jump to content


Photo

The algorithm behind "direction" and "speed"?


  • Please log in to reply
5 replies to this topic

#1 seesig

seesig

    GMC Member

  • New Member
  • 17 posts

Posted 08 December 2011 - 09:46 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 :P

Thanks in advance!
  • 0

#2 DanRedux

DanRedux

    GMC Member

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

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.

Edited by time4dan, 08 December 2011 - 09:48 PM.

  • 0

#3 seesig

seesig

    GMC Member

  • New Member
  • 17 posts

Posted 08 December 2011 - 09:49 PM

Thank you very much!
  • 0

#4 TheSnidr

TheSnidr

    That guy

  • Global Moderators
  • 3017 posts
  • Version:GM:Studio

Posted 08 December 2011 - 09:52 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: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...
  • 0

#6 DanRedux

DanRedux

    GMC Member

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

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users