Flambe snippet: game heartbeat

Code snippets, Games, Haxe

This is a post about a gameplay-element that affects how game objects can be triggered on a certain “heartbeat”. This relative simple component brings some interesting features.

I created a code component that can be used in Haxe Flambe framework. Flambe is a 2D game cross-platform (HTML5, Flash, iOS, Android) gaming engine.

The idea of this component is that all objects in the game listen to a global heartbeat and respond to it. Think of a rhythm in music, where elements are triggered at different notes in a beat.

I used it in my game to trigger spikes and shoot bullets, but you could also use it for other things of course. The problem I first had was that platforms were added to the level on random time, based on when player y position. This causes every platform to have its own rhythm, which makes it harder to play and a bit unpredictable for the game player. Therefore I wanted a global timer.

The heartbeat component

How to use

If you put the heartbeat in the game container Entity, you can access it from the game objects using the owner.getFromParents function (new since flambe 4.1)

I added a value called beats per minute that defines the speed. The higher this value, the shorter the delay between each beat. A nice thing about is that you can change it because it is variable. In my game, I raise the heartbeat slowly, to make the game more difficult when the player gets further. When user gets very far, cannons shoot with very short delays and spikes come up fast; the player has to react very fast. That is a cheap but very effective way to put some progression in a game 🙂

You could also use this component to sync your game somehow to music, if you can determine what the beats-per-minute (bmp) is. Or you could even use it to play own samples to make simple music or compose beats.

To illustrate, the beat (when ticksPerBeat = 4) goes like:
0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0 etc..

To listen to that beat in your game object, you can do this:

I hope you like it.

Say something interesting

Please link to code from an external resource, like gist.github.com.