Implement a walking animation for a 4-way sprite character
Verification environment
- Windows
-
- Windows 11
- Unity Editor
-
- 2020.3.25f1
- Input System Packages
-
- 1.2.0
Prerequisites for this tip
The following settings are pre-configured as a prerequisite for the explanation of these tips.
Reference site
Preparation of walking graphics
First of all, the walking animation is achieved by constantly switching between multiple images to make it look like you are walking. Therefore, it is necessary to prepare as many images as necessary to show the direction of movement and walking.
In order to achieve the simplest walking animation, it is common to prepare the following image. This pattern is also used in many RPGs.
First of all, it is divided into four lines above and below, but it shows the direction you will face when you walk. From the top, it is "down, left, right, up".
And for the left and right, it will be a walking motion in that direction. The general flow is "middle, left, middle, right, middle...".
The size of one cell of the character prepared this time is 32x32px. Since it is prepared for 3x4 squares, the actual size of the image file is 96x128px. By the way, there is no limit to the size of one character, so 32x48px or 64x64px is also possible.
* The image prepared this time is Iwamaru-kun, which I made a long time ago. You can use it as a behavior verification.
Create a project and prepare images
In the sample we will create this time, we will assume that you can place a character and move it with the cursor keys on the keyboard.
The first step is to create a new 2D project. Add the character image you prepared for your project.
Select the image you just added and configure the following settings in the inspector:
Item Name Value | Remarks | |
---|---|---|
Texture Type | sprite | |
Sprite Mode | plural | |
Number of pixels per unit | 32 | Affects the size when placed in view |
Mesh Type | Full Rectangle | |
Filter Mode | point | If necessary |
compression | without | If necessary |
After setting, click the "Apply" button at the bottom.
Next, split the image so that you can switch between them in Unity. There is a "Sprite Editor" button in the inspector, so click it.
When the Sprite Editor dialog appears, click the "Slice" drop-down, set the "Type" to "Grid By Cell Size", Enter a pixel size of 32 (depending on the size of your character) and click the Slice button.
Then, the image will be split by the specified size. If it's confusing, press the Ctrl key to see a dividing line.
After splitting, click the "Apply" button to close it.
If you click the circle right button of the image file in the project to expand it, you can see that the image is divided.
Creating Animation Data
Drop the image created in the previous section into the view.
Then, instead of adding the image, a save dialog will be displayed. This will save the animation settings, so for the time being, save it as "< image name >Animation.anim".
This will create two files in the project, with the split image in the view and the later image in the view.
By the way, if you run the game in this state, I think the character will animate on its own. This is a state in which 12 images are switched and displayed at any time.
If the game is running, quit it and select the Animations tab. If not, select "Window -> Animation -> Animation" from the menu.
You have selected the object that you created from the hierarchy (in this case, Iwamaru_0).
There is already an auto-generated animation, but I don't need it, so I'll delete it later. There is a drop-down called "IwamaruAnimation" that I named this time, so click on it and select "Create New Clip".
Then the save dialog will appear. Since we will create an animation of the down movement, we will leave it as "Iwamaru Down".
Select "Iwamaru_0" from the hierarchy and change the animation to "IwamaruDown".
This time, we will repeat the animation in "left, middle, right, medium", so we will set the number of samples to 4. Then the timeline on the right will be divided into 4 parts.
Drop the Iwamaru_0, the image in the upper left corner of the project, onto 0.0 in the animation timeline.
Next, drop the "Iwamaru_1" in the middle image above to 0.1 and 0.3.
Finally, drop the "Iwamaru_2" in the upper right image to 0.2.
When you're done, click the play button. You can see that the character in the view is walking and animating. (This sample image is a little difficult to understand, but ...)
Follow the same steps to create left, right, and top animations.
Animation file name | setting image |
---|---|
IwamaruDown | Iwamaru_0, Iwamaru_1, Iwamaru_2, Iwamaru_1 |
IwamaruLeft | Iwamaru_3, Iwamaru_4, Iwamaru_5, Iwamaru_4 |
IwamaruRight | Iwamaru_6, Iwamaru_7, Iwamaru_8, Iwamaru_7 |
IwamaruUp | Iwamaru_9, Iwamaru_10, Iwamaru_11, Iwamaru_10 |
The end result should look similar to the image below.
Make sure that each direction animates correctly.
Animation transition settings
Next, double-click "Iwamaru_0.controller" from the project to open it.
Then the Animator tab will open and you will see a screen like the one shown in the figure. This is because the animation you just created is ". controller" file.
Right-click on an empty space and select Create State -> From New Friend Tree.
A new "Blend Tree" will be created, right-click on it and select "Set Layer as Default State".
The Entry will then look at the Blend Tree. This means that when the animation moves, the Blend Tree will be the first thing to move.
We're going to set up animations in Blend Tree, so we'll delete all existing animations.
There is a "Parameters" tab on the left, so select it and add "Float" from the + button.
Since there are two parameters, they are named "X" and "Y" respectively.
Double-click the Blend Tree.
Select the Blend Tree that appears.
From the Inspector, change the blend type to 2D Simple Dictional.
Set the Parameters to "X" and "Y".
From the + button in Motion, select Add Motion Field 4 times.
The initial value may be different, but it should look like the figure.
For the four Motion items we added, we will set the top, bottom, left, and right .anims in the project.
Then, specify which direction each animation should move.
Direction | X | Y |
---|---|---|
under | 0 | -1 |
top | 0 | 1 |
left | -1 | 0 |
right | 1 | 0 |
This completes the animation setup.
Finally, you can delete the automatically generated animation file because you don't need it.
Movement control
Movement is done by pressing a key on the keyboard, so you can create a script to control it. This time, the script will be attached to the character, so we will leave it as "CharacterMove".
The script looks like this:
using UnityEngine;
using UnityEngine.InputSystem;
public class CharacterMove : MonoBehaviour
{
// あらかじめ Animator コンポーネントを持っておくようにする
private Animator _animator;
// 最初のフレーム更新の前に開始が呼び出されます
void Start()
{
// オブジェクトに紐付いている Animator を取得する
_animator = GetComponent<Animator>();
// 最初の向き (下) を設定する
_animator.SetFloat("X", 0);
_animator.SetFloat("Y", -1);
}
<summary>一定時間ごとに呼ばれるメソッドです。</summary>
void FixedUpdate()
{
// キーボードの入力方向を取得
var move = GetMove();
if (move != Vector2.zero)
{
// 入力されている場合はアニメーターに方向を設定
_animator.SetFloat("X", move.x);
_animator.SetFloat("Y", move.y);
// 入力した方向に移動
transform.Translate(move * 0.2f);
}
}
<summary>キーボード入力による移動方向を取得します。</summary>
<returns>キーボード入力による移動方向。</returns>
private Vector2 GetMove()
{
Vector2 move = Vector2.zero;
if (Keyboard.current.upArrowKey.isPressed)
{
move += new Vector2(0, 1);
}
if (Keyboard.current.downArrowKey.isPressed)
{
move += new Vector2(0, -1);
}
if (Keyboard.current.leftArrowKey.isPressed)
{
move += new Vector2(-1, 0);
}
if (Keyboard.current.rightArrowKey.isPressed)
{
move += new Vector2(1, 0);
}
// 入力した値がある場合は正規化して返す
return move == Vector2.zero ? move : move.normalized;
}
}
The following is an explanation of each part.
// あらかじめ Animator コンポーネントを持っておくようにする
private Animator _animator;
// 最初のフレーム更新の前に開始が呼び出されます
void Start()
{
// オブジェクトに紐付いている Animator を取得する
_animator = GetComponent<Animator>();
// 最初の向き (下) を設定する
_animator.SetFloat("X", 0);
_animator.SetFloat("Y", -1);
}
Start
First, get the component in the Animator
method. Update
This will be used in , so have it in advance.
Animator.SetFloat
The method can set a value for the specified parameter name.
In the animation settings, we set which animation to use according to the X and Y values.
If you set the direction of the X and Y parameters, the animation will be executed in that direction.
In the initial state, we want to face down, so we specify (X: 0, Y: -1).
By the way, note that parameter names are case-sensitive.
<summary>一定時間ごとに呼ばれるメソッドです。</summary>
void FixedUpdate()
{
// キーボードの入力方向を取得
var move = GetMove();
if (move != Vector2.zero)
{
// 入力されている場合はアニメーターに方向を設定
_animator.SetFloat("X", move.x);
_animator.SetFloat("Y", move.y);
// 入力した方向に移動
transform.Translate(move * 0.2f);
}
}
FixedUpdate
In the method, we periodically check the input status of the keyboard and process it when there is input.
GetMove
The method is designed to return directions as the keyboard inputs.
The processing content is based on what is described in Keyboard Input Tips, so I will omit it.
When there is keyboard input, Animator.SetFloat
set the direction to the method. This enables animation in the direction you moved.
transform.Translate
After that, we are moving the object with the method.
Once you've created the script, attach it to the character object.
execution
This completes the whole process. Try running the game and pressing the cursor keys on your keyboard to move it. If the character moves in the direction you pressed it, and the walking animation moves while the graphic changes direction to the direction you are facing, you're done.