Game Development Reference
In-Depth Information
1:
var instance;
2:
instance = instance_create( x, y, obj_enemy_die );
3:
instance.speed = 4;
4:
instance.direction = random( 180 );
3.
These lines are comparable to a
Create Moving
action and they get called four times to
create four instances of
obj_enemy_die
. However, the
instance_create
function (line 2)
also calls the
Create
event of
obj_enemy die
before it reaches lines 3 and 4, so we'll go
there next to remind us what that does.
4.
Select the
Create
event of
obj_enemy_die
and observe these lines of code within its
Execute Code
action:
sprite_index = global.die_sprite_index;
image_index = random( image_number-1 );
This sets the sprite to be the same as the one held in the global variable and then
randomly assigns a subimage (a random piece of the exploded enemy sprite). In this
case, that would be
spr_beastie_die
, but each enemy object sets the global variable to
an appropriate sprite before the instances of
obj_enemy_die
are created. In this way,
each instance of
obj_enemy_die
can have a different sprite, but still share identical
object behavior. It saved us from having to create a new dying object for each different
kind of enemy in the game.
You can summarize this technique as using a global variable to provide information (the
appropriate sprite to use) to a newly created instance. However, we can already see from lines
3 and 4 of step 2 that it is possible to do this in a more elegant way in GML—and avoid using
global variables altogether!
■
Note
We will sometimes add line numbers to larger sections of code so that it's easier to reference
different parts of the code in the text. These do not correspond to the line numbers in the
.gmk
file, and are
purely for the purposes of the topic, so there's not need to worry when they don't match up.
Within zoolgml.gmk
1.
Open up
obj_beastie
and select its
Destroy
event. Of course you can't, as there isn't
one! The old
Destroy
event simply set the value of the global variable and we're not
using that anymore, so there is no need for the
Destroy
event in
obj_beastie
at all.
Open up the
Create
event of
obj_beastie
instead, and observe this line:
die_sprite_index = spr_beastie_die;
This time, we're setting a local variable (which we've chosen to give the same name as
our old global variable) to hold the correct dying sprite for the Beastie enemy.
Search WWH ::
Custom Search