2D Player Setup (3): Attacks!
The majority of the changes needed for this attack animation were in Unity rather than in any script, but I’ll start with the main code adjustment 😉
From Update in the Player class, I’m now calling a “Player_Attack” method. This just checks to see whether the left mouse button has been pressed and that the player’s currently grounded, and if these are both true then it calls the public “Attack” method on the PlayerAnimation class we looked at previously. I’ll include these snippets below:
Animations and Animator Controllers
As you might have noticed in the previous article, I’ve added a Player_Attack Animation State with connections running between it and both the Player_Idle and Player_Run state. From either of these states, if an “Attack” boolean parameter is set to true then we transition into the Player_Attack state (playing an attack animation I set up in the same way as the other animations). I’m then using the “Velocity” float parameter to decide whether we should transition back from this to either Player_Idle or Player_Run, depending on whether its value is greater than 0.1.
For the sword animation effect, this involved creating a child GameObject with a SpriteRenderer and an Animator component, creating a simple Animator Controller, and adding a 2D sprite animation using a sliced sprite sheet.
The “Neutral” Animation State also has an animation on it, which sets the SpriteRenderer’s Sprite to null. This just ensures we can’t see anything until the SwordArc animation is called using the “Attack” trigger, but you could also just set the alpha value on the sprite to 0 within this Neutral animation.
A quick note on setting up the animation itself, you may need to include some sort of delay/pause within the animation before it properly plays, just to get it to sync up with you Player Sprite’s animation. In my case, a 5 second delay seemed to work nicely enough:
The rest of the setup mainly consists of positioning, scaling, and angling this effect (in 3D space) until you’re happy with the result. This is potentially easier said than done, but do have a go experimenting with the angle in particular if the arc doesn’t quite work with the Player Sprite’s attack 😉 Happy Animating!