if then else

Blitz3D Forums/Blitz3D Programming/if then else

Rook Zimbabwe(Posted 2004) [#1]
I have music in my game and I wanted the user to be able to toggle it off and on so I wrote this:
If KeyHit (50)=True And musicflag = 0 Then musicflag = .5 Else musicflag = 0
Now the music is playing on a channel and musicflag is the volume represented here:
ChannelVolume play_annoy,musicflag
play_annoy is the music channel. The music loops because in the front of the program I loaded it as:
Global annoy=LoadSound("media/heroloop1.ogg")
LoopSound annoy
play_annoy=PlaySound(annoy)
I can't make this work... it never comes on except for a brief splash as the program starts.

What am I doing wrong?


Matty(Posted 2004) [#2]
Firstly - if musicflag is an integer not a float then it will always be set to zero (as it will round down from 0.5 to 0).

A better way would be to do the following:
At the start of the game set Musicflag to 0.
then do this:
If KeyHit(50)=true then MusicFlag=1-MusicFlag

which will alternate it between 0 and 1 each time it is pressed.
then do this
If MusicFlag=1 then channelvolume PLay_annoy,0.5 else channelvolume Play_annoy,0



N(Posted 2004) [#3]
If KeyHit(50) >= 1 then MusicFlag=1-MusicFlag


KeyHit() doesn't always return just true (1)- it returns the number of times the key has been pressed since the last call to it. Just a little thing you might want to keep in mind just in case. Rarely if ever will it return above 1 for me.


Rottbott(Posted 2004) [#4]
I thought (anything except 0) == True.

Anyway, I reckon you're using an integer.


Neochrome(Posted 2004) [#5]
it does :)


AbbaRue(Posted 2004) [#6]
You may want to add the following lines to that or it will keep toggling on and off as you hold the key down.

.K50
If KeyDown(50) Goto K50 ;loop until key released


Matty(Posted 2004) [#7]
I wouldn't do as AbbaRue suggested unless you want your game to pause while you hold down the key.


AntonyWells(Posted 2004) [#8]
lol@paused program.

Do this,

 MusicFlag=(keyhit(1)>0)

The ifless optimization


John Pickford(Posted 2004) [#9]
That will reset the music flag to zero except for a split second when you hit key (1).

Noels solutions will work.


AntonyWells(Posted 2004) [#10]
So it will. (Egg on face)


Rook Zimbabwe(Posted 2004) [#11]
Noel and Matty... excellent suggestion! All of you thank you for that help... :)
-RZ