2D Character Setup in Unity — Attack Animation
This article will show how to set up a sword swing for a 2D character when the Player presses the left mouse button. We will also add an animation for a sword arc effect to make the sword swing more visible.
Animator Controller for the Player is set up to play the Attack animation when the Attack Trigger is set. Then goes back to playing the Idle or Run animation.
The Sword Arc sprite animation functions like the Attack animation on the Player sprite but is a separate child of the Player GameObject so that it can be swapped out or turned off.
In the Player Animator script, we add a reference to the Animator on the Sword Arc and grab it by getting the second child of the Player. To do this, we use GetChild and pass in the second index of 1.
The Player script calls this method. It sets the Trigger on both Animators playing the attack and sword arc animations.
In the Player script, we need a few variables to control the attacking.
- The amount of time to delay before allowing the Player to attack again.
- A reference to the Sword Arc Sprite Renderer to flip it with the Player.
- A bool to know if the Player is currently attacking.
This Coroutine sets the attacking bool to false after the attack delay, allowing the Player to attack again.
In Update, if the Player presses the Left Mouse button-down, is on the ground, and is not already attacking, we call the Attack method on the Animation script, set attacking to true, and start the Attack Delay Coroutine.
In the Flip method, we add the Sword Arc Renderer to be flipped with the Player, so the animation lines up with the Player’s attack.
The Player now attacks when the Left Mouse Button is pressed.