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.

  1. The amount of time to delay before allowing the Player to attack again.
  2. A reference to the Sword Arc Sprite Renderer to flip it with the Player.
  3. 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.

--

--

--

Unity Developer, Software Engineer, Game Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Simple Momentum Tool for Stock Selection

Feature: Health Pickup

Storing and Transforming Images using Cloudinary: A Simple Guide using the Fetch API

Backtesting Basis Trading

Run GUI Software Inside Container

Q&A: How Eventbrite prioritizes developer productivity

C#/VB.NET: Convert Excel to CSV and Vice Versa

SandCat — Update 2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kyle W. Powers

Kyle W. Powers

Unity Developer, Software Engineer, Game Developer

More from Medium

Creating a Physics Based Character Controller from Scratch in Unity

Creating Enemy Explosions

Making a RTS game #39: Boosting our game scene (Unity/C#)

2D Mobile: Loot System