Your first game! Part 4: Parent objects

Posted on: March 31, 2015 at 6:39 pm,

Splitting up asteroids

Inside of obj_asteroid we want to create logic that says “when this object is destroyed, create two new smaller asteroids.”

Doing this is very straightforward, first of all, add the Destroy event. As you might guess, this event triggers whenever the object is destroyed (such as when we shoot it.)

drag in an “execute code” action and simply write the following:


instance_create will generate a new instance of a given object, just like when we used it to create bullets in part 2. Here we want to create two small asteroids at our current x and y coordinate so we just run this line of code twice.

now there’s only one major problem with this, and that’s that our smaller asteroid, obj_asteroid_s, is currently inheriting all of obj_asteroid’s code!

This means that when the smaller asteroids are destroyed, they will also create two new asteroids, which is not what we want. When the smallest asteroids are destroyed they should stay destroyed otherwise we’d have an infinite number of asteroids to deal with.

Fortunately there’s a straightforward way to deal with this. A child object only inherits events from its parent that have not been defined in the child object itself. So if we create a destroy event in the child object, it will run that destroy event and not the event of its parent. (although it is possible to still call the parent’s event through the “call inherited event” action as well as doing different things in the child event.)

So simply open up obj_asteroid_s and add the Destroy event. Now we would be done, but GM will remove any event that has no actions defined for it. So drag in an execute code action and simply write a short comment such as:

///do nothing

This obviously… does nothing, but means that the small asteroid will run this event in place of its parent’s destroy event.

You can now run this and observe your asteroids splitting in two when shot!


Next up we’ll be looking into tracking a score on the screen which will teach us a little more about variables and drawing stuff to the screen!

Pages: 1 2