Game Development Reference
In-Depth Information
4.
Add a
Step
,
Step
event and include an
Execute Code
action. Insert the following lines:
1:
{
2:
var dx, dy;
3:
hspeed = keyboard_check(vk_right)-keyboard_check(vk_left);
4:
vspeed = keyboard_check(vk_down)-keyboard_check(vk_up);
5:
if ( hspeed != 0 ) vspeed = 0;
6:
speed *= 4;
7:
if ( speed != 0 )
8:
{
9:
switch ( direction )
10:
{
11:
case 0: sprite_index = spr_explorer_right; break;
12:
case 90: sprite_index = spr_explorer_up; break;
13:
case 180: sprite_index = spr_explorer_left; break;
14:
case 270: sprite_index = spr_explorer_down; break;
15:
}
16:
image_speed = 0.5;
17:
} else image_speed = 0;
18:
dx = lengthdir_x(speed,direction);
19:
dy = lengthdir_y(speed,direction);
20:
if ( place_meeting(x+dx,y+dy,obj_wall) ) speed = 0;
21:
}
This script requires some explanation. Line 2 first defines two variables that we wish to
use only in this script. Lines 3-4 set the vertical and horizontal speed, dependent on
the state of the arrow keys. We've taken advantage of the result of
keyboard_check
,
which either returns
1
(
true
) if the key is pressed or
0
(
false
) otherwise. These values
are used to calculate a vertical and horizontal speed. For example, if
vk_right
(the right
arrow key) is being pressed while
vk_left
(the left arrow key) is not, then the outcome
is
1-0 = 1
. The other way around, if
vk_left
is being pressed but
vk_right
isn't, then
the outcome is
0-1 = -1
. If neither are being pressed, then the outcome is
0-0 = 0
and
if both are being pressed, then the result is
1-1 = 0
. This is correct as it shouldn't go
left or right on either occasion.
Line 5 limits the speed we have computed to only horizontal or vertical
movement, just in case the player is pressing both a left/right key and an up/down key.
Line 6 multiplies whatever speed we ended up with by four so the explorer actually
moves faster than one pixel per step.
Lines 7-17 change the sprite and animation speed, depending on the current
speed
. One cool thing about Game M
aker is that when we change
hspeed
and
vspeed
,
then the variables
speed
and
direction
are automatically adjusted. So, Line 7 first
makes sure that
speed
doesn't animate it, because we only want to change the sprite if
a key was pressed. Lines 9-15 then check the direction and change the sprite
accordingly (
0
for right,
90
for upward,
180
for left, and
270
for downward).
Line 16 sets
image_speed
to
0.5
to animate the sprite, while the
else
statement
doesn't animate it if the speed was 0 to begin with.
Lines 18-20 deal with running into walls. The
lengthdir_x
and
lengthdir_y
functions help us calculate how much the instance would travel horizontally and
vertically with the current
speed
and
direction
. We then check if there is a wall in that
direction. If there is, we set the
speed
to
0
to prevent the explorer from going that way.
Search WWH ::
Custom Search