Level 05 Lesson 02 [Global vs Instance Variables]

We’ve been making good use of variables in the past few lessons. The variables we have been using are called instance variables because each instance (object you create in the game) keeps the variable inside of itself. There are other types of variables in programming. One type is a global variable. Global variables are not owned by any individual object. They are owned by the entire game and any object is able to make them, change them, or check them. This lesson will introduce you to global variables and describe when using a global variable is better than using an instance variable.

Part A – Global Variables, Why we need them.
Watch the video: 05-02-A


Part B – Using Global Variables to replace common values
Watch the video: 05-02-B
Donefile: L05-02-B-Done.gmk


Challenge 1– Add some more Global variables
Continue with the project from the videos
L05-02-B-Done.gmk
and complete the following tasks:

a) make a global variable to keep track of what level the player is currently on. The first room is level 1. When the player touches the door and advances to the next room, increase the level variable by one.  Also draw this variable to the screen.

b) make a global variable to keep track of the number of times the player has hit a ghost with a laser. Increase this variable when ghosts get hit by lasers. Draw to screen.

c) make a global variable that will keep track of how fast the player laser will move when created.  Set the value of the global variable to 8 (this is the current speed of lasers).  When the player creates a laser you should set the speed of the laser to  this global variable (not the number 8). Now add the code so that when the player has earned 5 ghost hits, the global laser speed will change to 12.  When testing you should see the laser speed increase after the player has 5 ghost hits!

Challenge 1 Solution
Solution Video: 05-02-X1Solution
Solution File: L05-02-X1-Done.gmk