Followers 0

# Handling one-off events

## 6 posts in this topic

Hi everyone,

In my game I sometimes want one-off events to happen in the game loop, for example, I want a footstep sound to play when I have travelled past a certain distance. However, since I'm handling it in the game loop, I can't see how I can get this to happen. I think it's best to illustrate my problem with pseudocode:

while True: //Game loop
{
if (movingForward){distanceWalked += 0.1}
if (distanceWalked > 1){playSound(footstep.wav)}
}


As you can see, this code will wait until the user has walked a distance of 1, and then will CONTINUALLY re-play the footstep sound on every iteration of the loop. What I actually want is for it to play just once, when the user has walked passed a distance of 1. I can't think of an easy way to do this that doesn't involve assigning a boolean to every sound and handling that, which seems kinda awkward when I'm trying to make a game with possibly hundreds of sounds. Is there an easier way around this problem?

Thanks!

0

##### Share on other sites

If you're working with unique sounds, the boolean you speak of is directly a property of the sound itself, i.e. you only play the sound if it is not already playing:

while True: //Game loop
{
if (movingForward){distanceWalked += 0.1}
if (distanceWalked > 1 && isSoundPlaying(footstep.wav) == false ){playSound(footstep.wav)}
}

If you need to use the footstep sound for multiple entities, meaning you have to play multiple instances of the same sound, the best approach would be to have some kind of "sound manager" that in some way accepts events, and in return plays the appropriate sound. The manager would have to keep a list of all actively playing sounds, and also track which sound belongs to what entity.

May sound complicated, but if you do it wisely, it'd look no different than the code above:

while True: //Game loop
{
if (movingForward){distanceWalked += 0.1}
if (distanceWalked > 1 && soundManager.isSoundPlaying(this, footstep.wav) == false ){soundManager.playSound(this, footstep.wav)}
}

Above example uses the "this" pointer for the sound manager to use as a reference of the object calling it so it can track who the sound belongs to. This could also be a globally unique ID, or anything else really.

Edited by TheComet
0

##### Share on other sites

While assuming your sound plays only once when you call "playSound", the following might be all that is necessary:

while True: //Game loop
{
if( movingForward ){distanceWalked += 0.1}
if( distanceWalked > 1)
{
playSound( footstep.wav );
distanceWalked = 0; // just reset your counter here
}
}
Edited by Charon
1

##### Share on other sites

The solution is simple, you just have to think about it. When you start walking, initialize a variable to zero, then, using a timer, increment it by the time elapsed until it's greater or equal than one second, if so, play the sound, and reset the variable. Also reset the variable when you stop walking. Sorry, i misread your post, i though you said 1 second, just do what Charon said.

Edited by Vortez
0

##### Share on other sites

the whole game could be (and most of the time should be) run solely by events.

While it's possible to create a fully event-driven game; there are often times where that hammer just isn't the right solution for what you're trying to do.  Polling shared state can just as easily be used to make decisions about what to do next.  For example:

void PlayerSoundSystem::Update(float dt)
{
bool stopped = false;

//! Get the current position and check if the player is actively moving
const Vector3& position = GetPlayerCurrentPosition();
if(!GetIsPlayerCurrentlyMoving())
stopped = true;

//! Compute the distance moved and store reference to current position.
mDistanceMoved += (mPreviousPosition + position) * dt;
mPreviousPosition = position;

//! If distance equals or exceeds 1 world unit, fire.
if(mDistanceMoved >= ONE_WORLD_UNIT)
{
const GroundType& groundType = GetCurrentGroundMaterialType();

//! If sound actively playing now, exit routine.
//! This will allow mDistanceMoved to continue to accrual until
//! either the player stops moving or the current sound ends and
//! will then be replayed again.  It also makes sure the ground
//! types haven't changed as a new sound will then be necessary.
if(IsPlayingSoundNow())
{
if(mPreviousGroundType == groundType)
return;

StopPlayingSound();
mPreviousGroundType = groundType;
}

switch(groundType)
{
case GroundType::WATER:
PlaySound(PLAYER_SWIMMING_SOUND_FILENAME);
break;
case GroundType::SNOW:
PlaySound(PLAYER_WALKING_SNOW_FILENAME);
break;
/* other options */
default:
PlaySound(PLAYER_WALKING_DEFAULT_FILENAME);
break;
};
}

if(stopped)
{
mDistanceMoved = 0; /* reset when player stops moving */
StopPlayingSound();
}
}


2

##### Share on other sites

It depends, as always. Event-driven programming has its advantages and disadvantages, much like everything in the world. All major windowing systems (such as Windows or X11) are event-driven, they'd hardly be if there weren't some obvious advantages to that approach as well.

Most importantly, it makes your program (which does not need to be a game) more flexible. Getting back to the walk-2-secs-before-dropping-dead example, adding such a thing means having to substantially rewrite program code. Using an event-driven approach, it means (in the most extreme case) to modify a script, possibly even after the game has shipped. Running scripts to respond to events is not only a possibility, but something that is actually done in many real games.

Say that the team working on your game's next expansion pack decides for a ring-of-instant-revive item (maybe some kind of "premium" item, or a "rare drop" that you can loot, whatever). When your character dies, and one of the 3 charges on the magic ring remains, the character is revived. How do you implement this? How do you implement all the special cases for the other already existing 75 equipment items in your game?

Given events, you're firing an event whenever an item is picked up (or bought from the shop, or equipped, whatever), which does nothing most of the time.

Now for that particular item, you let your artist create a fancy picture for that new ring, and add a script that is run on the PICK_UP (or EQUIP) event, which registers a handler on the YOU_DIE event (and, if you can drop/unequip items in the game, one on DROP). The handler script on YOU_DIE restores some health and returns "do not continue handlers". Which effectively prevents the default YOU_DIE handler from running, and presto, the magic works.

It may not be the most straightforward way of thinking, and I can see your argument how debugging may be a little harder, but on the other hand you gain a lot of flexibility, without a need to modify and rebuild the program, and re-distribute a 50-100MB executable.

Edited by samoth
1

##### Share on other sites

It depends, as always. Event-driven programming has its advantages and disadvantages, much like everything in the world. All major windowing systems (such as Windows or X11) are event-driven, they'd hardly be if there weren't some obvious advantages to that approach as well.

I believe L. Spiro would even agree there are appropriate places to use events in a game engine and the GUI side is most certainly one of those cases.  But despite their usefulness in this arena, operating systems themselves don't rely on them much beyond the UI interaction and some corner cases that often could be implemented without using event/messages.

Most importantly, it makes your program (which does not need to be a game) more flexible. Getting back to the walk-2-secs-before-dropping-dead example, adding such a thing means having to substantially rewrite program code. Using an event-driven approach, it means (in the most extreme case) to modify a script, possibly even after the game has shipped. Running scripts to respond to events is not only a possibility, but something that is actually done in many real games.

Flexibility is often a necessity for various reasons you've pointed it, but it does come with it's own share of consequences and side effects that must be managed well.

I often see developers try to implement the mediator pattern and while it has uses in certain places, I believe it really blurs dependencies too much in large scale code bases.  It's often been argued as a means for rewind/replay game play.  It works generally, but I dislike the concept.  I prefer explicit dependencies between aspects of the code base rather than hiding them.  Rather than using the mediator for rewind/replay, it's just as easy to have the rewind/replay system just subscribe to all objects of interest and when they emit an event, cache/log it and not have some central event manager mediate the dispatch of events.  This way it doubles as a logging mechanism in debug builds and if rewind/replay isn't needed for the released title, it just doesn't get turned on in those builds.

Edited by crancran
0

## Create an account

Register a new account