The last few demos have shown different uses of the SineOscillator behaviour, this demo introduces triggers and a proper implementation of object pooling. In this demo an Orb is added to the center of the Canvas with behaviours added to randomly move it around. An Orb is added every third frame, however it is only added if there is one available in the object pool. In this demo the object pool has a limit of 50 objects, the current object count is displayed to illustrate the number of objects on the canvas, you’ll notice that it never goes above 50.
Triggers are added to each orb created; a trigger is something that calls a function when it’s conditions are met. In this case we’re using the ExitBoundsTrigger, which is triggered when the Orb is out of the bounds specified (the Canvas area). The function called by the trigger recycles the target object by removing all behaviours and releasing it back into the object pool ready for it to be used again. I’ve also added the ability to toggle whether the canvas captures the individual frame, or the series of frames, click the image below to see it in action.
Below, I’ve included the source code of the demo. You can have a look through all of the code properly on GitHub, but I’ll give a quick overview.
If you’ve been following along, you’ll see that this demo uses many of the classes we’re already familiar with, such as the ColorPool, ObjectPool and the BehaviourManager. In this post we’re introducing the concept of triggers, as well as the TriggerManager to manage the triggers.
As mentioned above, in this demo we’re using the ExitBoundsTrigger, which is created in the onCreateObject function. The ExitBoundsTrigger takes three parameters; the target object, the bounds that confine the target and the function to be called when the target exits the specified bounds. The Bounds are specified in the init function, so far only a rectangle is supported.
When an Orb exits the bounds specified the onExitBounds function is called. This function removes the Orb from the CanvasController, thus removing it from the Canvas, releases it back into the ObjectPool and removes all behaviours and triggers for the object. Doing this allows us to reuse the objects already created in memory, rather than creating a new object every time one is requested.
This demo using a different method to release objects from the ObjectPool than used in previous demos. Previous demos have used requestAll to request all available object from the pool at once, this demo requests objects in the update function, on every third frame. By recycling the objects used we are able to continuously request and reuse objects from the ObjectPool.
You can grab the source code from GitHub and have a play.