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

Deploying a Gatsby Site to GitHub Pages Using GitHub Actions CI/CD

from Twitter https://twitter.com/build_online

CS371p Fall 2021: Sruthi Rudravajjala

Do I need test-driven development?

KYVE. Explanatory story. Testnet short guide.

Leetcode 317. Shortest Distance from All Buildings [Hard]

Docker Container MongoDB

Breadcrumbs… Not just for the birds!

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

Journal 147 — Unity Project Development, 2.5D Shooter

Creating enemy movement behavior

2D Mobile: Loot System

Making a RTS game #50: Implementing a technology tree 1/3 (Unity/C#)