Game Development Reference
In-Depth Information
Speaker
You will use the speaker actor to control the sounds and music. In this example,
you will only focus on sound but you could use the same approach with music.
A touch on the speaker will change the state of a game attribute to either 0 or 1.
You could use rules and Boolean, but instead I will show you a cool trick with
the modulo operator.
Wikipedia defines modulo operation as a function that returns ''the remainder of
division of one number by another.''
In other words, if you divide 9 by 4, you get 9 = 2 x 4 + 1. The remainder of 9
divided by 4 is 1. Let's take another example. If you divide 50 by 14, you get 50
= 3 x 14 + 8. The remainder of 50 divided by 14 is 8.
With modulo notation (%), you have 9 mod 4 = 1 or 9%4=1.
Now, if you take any number (integer) and you do modulo 2 this number, you
only have two possible results: 0 and 1. If the number is even, the remainder of
this number divided by two is null (0). If the number is odd, the remainder of this
number divided by two is 1.
So with a simple equation of a unitary increment and modulo two, you have a
result that goes from zero to one and from one to zero. The equation is soundOn
= (soundOn+1)%2.
By default, you want to have the sound on. So the initial value is soundOn=1.
When you press the Speaker actor, you get SoundOn = (1+1)%2 = (2)%2 = 0.
The next time you press the Speaker actor, you get SoundOn = (0+1)%2 =
(1)%2 = 1. And so on…
When you want to have sound, SoundOn is equal to 1 and when you don't want
to have sound, SoundOn is equal to 0. All the rules on sound are based on the
state of the SoundOn attribute.
To make it simple to manage, instead of creating a rule for every PlaySound
behavior, you will control the volume instead. When SoundOn is equal to 1,
volume is equal to 1. Respectively, when SoundOn is equal to 0, volume is equal
to 0.
You will also implement a rollover with a crossed speaker icon when the sound
is turned off.
Let's do all this now!
Create a new game attribute of type Integer and name it ''SoundOn.'' Give this
attribute the default value of 1 as per Figure 9-5.
 
Search WWH ::




Custom Search