Game Development Reference
In-Depth Information
Toggle Music and Sound Effects
No game can do without sound effects and some cool music to set the mood. But for all your
efforts in sound design, the player may not be as happy with your choices are you are. We should
give them the opportunity to switch either of them off. We can't simply set the global volume to 0,
as that will influence both at the same time, so there is a little more work involved. Most games
have configuration screens to do this, but flexible as we are, we allow users to toggle music and
sound effects at any time in the game, by either clicking on an icon or pressing a key.
Start with:
Reference/Framework/spaceship7.gmk
Creating Toggles for Music and Sound
1.
Add an object called
obj_music_toggle
and set its
Sprite
to
spr_music_toggle
. This will
be our music switch, which needs to always appear in front of other objects, so set the
Depth
to
-1000
.
2.
Add a
Create
event and include an
Execute Code
action. Insert the following lines:
1:
{
2:
if ( !variable_global_exists('playmusic') ) global.playmusic = true;
3:
image_index = global.playmusic;
4:
image_speed = 0;
5:
}
This code requires some explanation. We're going to keep track of whether music
should be played or not by using a global variable called
global.playmusic
. We use a
global variable so we can check this value in any room in the game. After all, if music
was switched off in one room, we shouldn't start playing again in the next!
We will let our music toggle create this variable and set it to
true
(play music) by
default, but we only do this if the variable does not yet have any value. This check is
required because it may already have been set in another room, and we don't want to
reset it, and we can't check a variable that doesn't exist. In short, using the function
variable_global_exists()
in line 2 makes sure the variable is properly initialized
without being reinitialized (remember that the Boolean operator
!
means
not
).
Line 3 sets the subimage to the value of
global.playmusic
. The variable will be
either
0
for
false
or
1
for
true
, so this nicely switches to the appropriate subimage. The
last line stops the sprite from animating.
3.
Add a Script resource and call the script
music_play
. We will be using this script
anywhere in the game where we want to play music, rather than using Game Maker's
action for playing sound. It will check for us whether or not the music should be played
at all. Insert the following lines:
1:
{
2:
global.music = argument0;
3:
if ( global.playmusic ) sound_play(global.music);
4:
}
This Script takes the music we want to play as its argument. The value of
argument0
is
stored in a global variable
global.music
so we can keep track of which music was
selected last in case we toggled it. Line 3 plays the music only if
global.playmusic
is
true
. In other words, if the music was switched off, nothing is played.
Search WWH ::
Custom Search