Game Development Reference
In-Depth Information
The preceding code can be copied directly into your object if you wish; however, it is re-
commended to manually type it as that will help you to remember and understand what
we are doing.
As you can see in the preceding code, we are simply initializing the variables we will need
so they are ready to go. We will be using the key variables to check for keyboard presses
in the step event and move our object.
The
max_spd
variable stores the maximum speed the object will be able to move in any
direction. While we could type this directly into our code, this variable creates an easier
way to change the speed of the object should we find it is too fast or slow.
We are now ready to program the movement code. Add a step event to our player object
and drag in another code block.
To make our object move, we need to first check for user input on the keyboard. Remem-
ber, we have our controls stored in variables, so they can be easily changed.
For this, we are going to use an
if
statement. We need to use the
keyboard_check
function to check whether the keys are being held down and apply our changes should the
statement return true.
This is the code for the left key:
if (keyboard_check(key_left)){
x-=max_spd;
}
As you can see in the preceding code, we use our
key_left
variable as the argument
telling the
keyboard_check
function which key we are looking for. So, the code is es-
sentially asking the game whether the key stored in the
key_left
variable is being held
down or not. If it is, we then subtract our
max_speed
variable from the object's current
x
position. This moves the object to the left as a result. If we add to the
x
position, the ob-
ject will move right. We are now going to do this for the right key.
Re-type the
if
statement or copy and paste the entire code onto a new line. Then, change
the
key_left
variable to
key_right
and change
x-=max_spd
to
x+=max_spd
.
This will tell the game to move the object to the right if the key is being held down.
Our code now looks like this: