Learn To Code Like Me: Physics!

Here’s my current physics method.  I can guarantee you that it will change before the end, but this version seems to work pretty darn well.  Today, I’d like to walk you thorough how to write a basic physics method which can be applied to any object in a side-scrolling game!  Please, not, this isn’t a beginners guide and some understanding of C sytle syntax are required.

//argument0 = gravity
//argument1 = vspeed_limit

//modify gravity
var temp_grav, temp_vspeed_limit;
if place_meeting(x,y,obj_water)
if vspeed > 0
then temp_grav = argument0*0.25
else temp_grav = argument0
temp_vspeed_limit = argument1*0.25
temp_grav = argument0
temp_vspeed_limit = argument1
gravity = temp_grav

//set gravity
if place_free(x,y+vspeed+1)
gravity = temp_grav
if vspeed > 0 move_contact_solid(270,vspeed+1)
if abs(vspeed) > 1 and vspeed < 0 then move_contact_solid(90,vspeed)
gravity = 0
vspeed = 0

//vspeed limit
if vspeed > temp_vspeed_limit and vspeed > 0 then vspeed = temp_vspeed_limit


I use GML which is a scripting language thats built into Game Maker: Studio, but it works lime just about any other C or Java style language so much of this code is usable in any project.  A method if basically your own personalized function, it has inputs and can have an output.  In this case, the output is movement of the object that called the method in a way that resembles gravity.  A method looks something like this when its called “method(argument0,argument1,…,argumentN)”.  In GML, methods are called scripts, after all, it is a scripting language, so I start every method name with a scr_, that way, when i enter scr_ in the editor, it’ll try to auto-complete with everything that starts with scr_, aka. all my scripts!  This script is called scr_physics and is a general script designed to be used for any and everything that you want to be effected by gravity.  Basically, the script checks for water, if water exists at the instances location, it will modify the gravity  accordingly.   Next some system generated variables like gravity are set, they are controld by the game engine itself, all I have to do is feed it a value and the game engine will move the player down for me, though I could easily write my own method for moving the play, the game makers works fine so why not use it.  FInall, I want to make sure that gravity won’t cause speed to increase finally, say if the player falls down a bottomless pit, so I limit my vspeed (vertical speed) with the final line.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s