Darkshore Grouper
Darkshore Grouper

Reputation: 713

iOS and Cocos2d - Play sound once in game loop

This is more of a general "best practice" question, so I don't really have an example. I'm just trying to figure out how people usually approach this.
Let's say I have a mainGameLoop method, scheduled to be called 60 times a second. In this method, I have all the logic for the current scene. Now, I want to play a sound effect using SimpleAudioEngine when a certain state occurs.
The issue is, once this state occurs, it stays like that for a while, which means my sound effect will be rapidly played over and over again until the state changes (after all, we're inside the game loop).
My usual solution for this, is to use booleans to play the effect only once. Problem is, I am now facing a larger number of different states and effects, which means quite a lot of booleans.

I was wondering if there's a better way people usually use when playing sound effects in the game loop.
Any suggestions?

Upvotes: 1

Views: 301

Answers (1)

CodeSmile
CodeSmile

Reputation: 64477

You need a "state changed" event. Whenever the state changes to "on" the sound plays. Since you have to record this state change there's hardly any way around providing a boolean to record each state.

Of course you wouldn't code each state separately. Let's say you have 100 game objects (ie fruits) and each fruit plays a different sound when collected, you'd have a fruit class with a "fruitType" variable. When a fruit is picked up, you can:

  • check if this fruit type is already "carried"
  • play a sound if it is not
  • select the sound based on fruitType

Upvotes: 1

Related Questions