Game Development Reference
In-Depth Information
9. Add a Step , Step event, include an Execute Code action, and insert the following lines:
1: {
2: if ( place_snapped(32,32) )
3: {
4: speed = 0;
5: image_speed = 0;
6: if ( !instance_exists(obj_explorer) ) exit;
7: var dx, dy;
8: dx = obj_explorer.x-x;
9: dy = obj_explorer.y-y;
10: hspeed = sign(dx);
11: vspeed = sign(dy);
12: if ( place_meeting(x+hspeed*32,y,obj_impassable) ) hspeed = 0;
13: if ( place_meeting(x,y+vspeed*32,obj_impassable) ) vspeed = 0;
14: if ( vspeed != 0 && hspeed != 0 )
15: if ( abs(dx) > abs(dy) )
16: vspeed = 0
17: else
18: hspeed = 0;
19: if ( speed != 0 )
20: {
21: instance_create(x+hspeed*32,y+vspeed*32,obj_reserved);
22: speed *= 2;
23: image_speed = 0.5;
24: switch ( direction )
25: {
26: case 0: sprite_index = spr_scorpion_right; break;
27: case 90: sprite_index = spr_scorpion_up; break;
28: case 180: sprite_index = spr_scorpion_left; break;
29: case 270: sprite_index = spr_scorpion_down; break;
30: }
31: }
32: }
33: }
It's a long script, so let's break it down. Line 2 should be familiar to you—it ensures
that all code in the following block (which relates to moving the instance) is only
executed if the scorpion is aligned with the grid. When it is aligned, lines 4-5 first stop it
moving and stop the sprite's animation. We do this because we can't be sure the
instance should still be moving after this event.
Line 6 checks if obj_explorer still exists. If it doesn't, we simply exit this script.
This is necessary because the rest of this script tries to locate obj_explorer and then
move toward it!
Lines 8-9 figure out where obj_explorer is relative to the scorpion. The line
dx = obj_explorer.x-x calculates the horizontal difference between the scorpion and
the explorer, while dy = obj_explorer.y-y calculates the vertical difference. Because
the scorpion may be further to the right or further down than the explorer, these
values may be negative.
Search WWH ::




Custom Search