Skip to content

A5 - Parenting

Suppose you have several objects that are similar but not exactly the same. For instance, maybe you have one power-up that fills your life up fully, another that fills your life up halfway, and a third that just give you just a small amount of life. If you programmed each of these objects separately, you would have a lot of code common to all of them. This is considered bad practice since it means you potentially need to debug the same code in multiple places.

This is where parenting comes to the rescue. GameMaker would allow you to create a parent object called life_powerup (for example) that contains code common to all the life power-ups. You could then create child objects for each of the specific types of life power-ups, containing just the code that differs for each power-up type.

Task 1 - Walk-Through of an example

This task can be done in a blank GameMaker project.

  • Start the same way you did in assignment 1 - make two sprites that are just squares, called spr_blue_squre and spr_red_square

  • Make two objects, and assign one of your sprites to each object, again just like in assignment 1. Call the obj_blue_square and obj_red_sqaure. Don't create any events yet.

  • Create a third object called obj_square. Give it a step event with the following code:

// Move horizontally
x += xSpeed

// Bounce off left and right walls
if (bbox_right >= room_width || bbox_left <= 0) {
    xSpeed *= -1
}
  • Go into obj_red_square and click the Parent button. Choose obj_square.

  • Go into events for obj_red_square. You should already see a grayed out step event, which has been inherited from obj_square. Add a create event and add just one line of code:

xSpeed = 3
  • For obj_blue_square, also add obj_square as a parent, and give it a create event that sets xSpeed equal to 2.

  • Drag a couple instances of each square type into your room, and run it.

You have now created a simple parenting example.

Task 2 - Item Collection

This task can be done in another blank GameMaker project.

Using whatever online resources you'd like to for help, create a simple game containing two objects: a player, and an item the player can collect. GameMaker offers a few ways to accomplish this. Nothing fancy is required of your sprites this time - they can just be solid squares if you'd like.

Once you have this working, create two or three item types that all have the same parent. The parent can contain the collision/destroy code, and the children can just be responsible for displaying the proper sprite. You might also consider adding in a points system, where each different item adds a different amount to a global.points variable.