We recently wrote a feature that enables us to call a function on a specific animation frame. This week we’ll take advantage of this system for our projectile attack. At the moment we are spawning projectiles as soon as we press the projectile attack key, which doesn’t look quite right. What we really want is for the projectile to spawn at the correct moment in the animation which is when the player’s character releases the bowstring.
Before we write the animation action I want to make one small change to C_Animation. As I was writing the code for this tutorial I noticed that I’ve used a map to store the animations. A map will store the entries in a specific order (sorted using caparison function ‘Compare’). As we don’t need the entries sorted we can swap to an unordered_map as they are generally faster for insertions and retrievals.
C_ProjectileAttack still needs access to this class so include our new file.
Include the new file in C_Animation and then use it as the third parameter in the AnimationList (which I’ve also changed to use an unordered_map instead of a map) and the animations collection.
With that done we can start on the goal for this week: spawning the projectiles as an animation action. The Animation class already has the functionality for adding frame actions but we don’t interact directly with it, instead we’ll write a function in the animation component that will. This way any component can retrieve the animation component and add an action.
I’ve numbered the first call to the AddAnimationAction so we can discuss it in more detail.
- We want to add an action to the projectile animation for this entity so we pass that as the first argument.
- In this instance, we are adding an action for the Up direction (we add actions for the other 3 directions directly after).
- The animation has 10 frames and we want to want the action to be run on the last frame so, and remembering that the count starts at 0, we pass 9 in as the third parameter.
- The fourth argument is the AnimationAction. It’s the function we want to run on the specified frame. If we look at the definition of AnimationAction:
using AnimationAction = std::function<void(void)>;