• Create Account

## Handling one-off events

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

8 replies to this topic

### #1george7378  Members

1419
Like
0Likes
Like

Posted 15 January 2014 - 06:25 AM

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!

### #2TheComet  Members

2673
Like
0Likes
Like

Posted 15 January 2014 - 06:46 AM

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, 15 January 2014 - 06:47 AM.

"I would try to find halo source code by bungie best fps engine ever created, u see why call of duty loses speed due to its detail." -- GettingNifty

### #3Charon  Members

661
Like
1Likes
Like

Posted 15 January 2014 - 06:59 AM

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, 15 January 2014 - 10:04 AM.

chaos, panic and disorder - my work here is finished

### #4Vortez  Members

2705
Like
0Likes
Like

Posted 15 January 2014 - 07:03 AM

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, 15 January 2014 - 07:05 AM.

### #5samoth  Members

8935
Like
3Likes
Like

Posted 15 January 2014 - 07:35 AM

You want to register and un-register to events (or to callbacks). Something like this:

EventManager->Register(MOVING, CheckWalked1Meter);
while True: //Game loop
{
if(movingForward){ WalkInfo(my_speed, my_boots); EventManager->Post(MOVING, w);}
}

...

void CheckWalked1Meter(EventArg* arg)
{
static float distanceWalked;

WalkInfo* w = (WalkInfo*) arg;
distanceWalked += w.howfar;

if(fabs(distanceWalked - 1.0f) < 0.01f)
{
EventManager->Unregister(MOVING, CheckWalked1Meter);
if(w.my_boots == HEAVY_BOOTS)
PlaySound("klonk_thud.wav");
else
PlaySound("footstep.wav");
}
}

The "event manager" or whatever you call it would be just a table of function-pointers, or possibly a table of lists-of-function-pointers. Whenever you call Post(), it verifies whether the table entry with the given code is empty (then it does nothing!), and if there are any function-pointers, it calls them.

Registering means putting a function's pointer into one table entry, unregistering removes it.

Your function is called every time your unit moves, and does its check whether it has moved far enough. When that happens, it un-registers itself, and plays the sound, exactly once. If your unit is hit by a lethal shot, so it can still walk 10 meters before dropping dead, you register an event handler that checks for a distance of 10 meters and then posts a YOU_DIED event.

Same thing could be done with a simple function pointer too (or even with a bool that you set to true once you've played the sound, and an if-clause), but while you're at implementing such a thing, you can as well make it general and reusable. You'll likely find use for other "events" too. Basically, the whole game could be (and most of the time should be) run solely by events.

Edited by samoth, 15 January 2014 - 07:41 AM.

### #6crancran  Members

489
Like
2Likes
Like

Posted 15 January 2014 - 10:35 AM

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();
}
}



### #7L. Spiro  Members

24827
Like
3Likes
Like

Posted 15 January 2014 - 07:59 PM

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

While events have their places in games, games are not event-driven and abuse of events leads to nothing but crashes and debugging nightmares.

It is already a clue for instability when you consider the most basic example of a character killed but able to walk for 2 more seconds before falling. When if before those 2 seconds are over a friend casts “Revive” and now the character doesn’t need to die in the remaining 1.6473 seconds? “Be sure to remember to cancel the death event.”
Any time you mentally say, “Be sure to remember…”, while developing a game, you are skating along the edge of an iceberg.

It may be a simple thing to remember in this example, but now you work in a company with many people working on the same project, making their own events. It is impossible to keep track of every single event everyone is adding and how they can impact other events, even if every single time you add an event you walk around to every single team member and ask if your event affects any of their events.
Eventually something slips through the cracks and you get events triggering at the wrong times etc.

Not only is mass use of events a mess in the first place, it isn’t really even the best hammer for the nail in most cases (to borrow words from crancran).
What if after being killed you can walk for 2 more seconds, but, each time you get hit during that time, the amount of time left you have to walk decreases by a fixed amount?
What do you do? Search for the event and change the time it has left? Good luck.

And don’t even get me started on debugging event-based systems. I’ll start myself on it.
You get unexpected behavior in your game simulation, tracked down to an event.
What sent the event? Do you have information about the sender inside the event?
Even if you do, there are 250 of the same type of object. The event was sent 2 seconds ago and only after playing for 10 minutes, so you have no choice but to restart the game since the faulty conditions are already gone.
Now how do you proceed? Breakpoint every issuing of that event, for every object, for every frame, and hope eventually that bad event will be one of them?

Finally you have logged everything about each object and that event and in 10 minutes you finally get the strange behavior.
Your logs are 300,000 events long between 250 objects and 10 minutes. Which send-off was the bad one??
What if it turns out not to be related just to that object, but its interaction with another object or scenery?

The main point is you severely limit how you can go about debugging. Breakpoints tend to be useless in helping to finding the source of a single bad event delayed by any amount of time with thousands of other events just like it but in good standing.
It’s just a nightmare (and I have to endure the same thing right now at work, though not related to events).

Events in games are for players reaching a certain point on the map, certain objectives being completed, etc.
They are not for running your game.  I have used event-based game frameworks before and I will never again.

As for timing things goes…
This applies to all posts above, not just to the poster.
When you have a floating-point timer that simply times how long until some action takes place, never count up, always count down to 0.

Not only does this save you memory (you don’t need to keep a variable indicating the time at which the time counter expires), it is faster (comparing against 0 is faster than comparing against a value that may or may not be in the cache), easier to manage (just decrease it; if it is below or equal to 0 trigger the action), and easier to tell how much time is left (if the value of the counter is 0.85, then there are 0.85 seconds left until the event).

This also gracefully handles the case where you can walk for 2 seconds after death (m_fDeathTime = 2.0f;), but each hit during that time takes off 0.2 seconds (m_fDeathTime -= 0.2f;) from your walking period.

if ( m_fDeathTime <= 0.0f ) { WaterGoDownTheHooooole(); }

L. Spiro

### #8samoth  Members

8935
Like
1Likes
Like

Posted 16 January 2014 - 03:52 AM

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, 16 January 2014 - 03:52 AM.

### #9crancran  Members

489
Like
0Likes
Like

Posted 16 January 2014 - 08:58 AM

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, 16 January 2014 - 09:00 AM.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.