2D Mobile Game: Finishing Enemy Movement

Intro

In this article, we are going to cover how to detect when a certain animation is playing so we can stop the enemy from moving when in idle. Also, we will flip the enemy sprite to face the way it is moving.

Animator Setup

In the Moss Giant Animator, we have the Idle animation as the default animation and have it transition to the walk animation after the Idle animation is finished playing. We will need to create a trigger parameter (Idle) to call when we are want to transition back to Idle from Walk.

Make sure the animation transitions are as follows…

The Script

The first thing we need to know is when the Idle animation is playing. We need to know this, so we can stop the enemy from moving while it is playing. So we declare an Animator variable (_anim) and get the Animator component in the child.

In the Update, we can check when a certain animation is playing by its name. We need to access the animator (_anim) and layer (Base Layer) that the animation is in.

Using GetCurrentAnimatorStateInfo through the animator and passing in 0 for the base layer, we can check for the Idle animation is playing using IsName.

When this is true we don’t want anything to happen, so we will return. If the Idle is not playing then we call the Movement method.

Now, we need to be able to flip the sprite image depending on if the Moss Giant is moving left or right.

We can accomplish this through the Sprite Renderer, so we get the Sprite Renderer component in Child (_mossSprite).

In the Movement method, if the current TargetID is 0 (this is the waypoint on the left), we will want to flip the sprite on the X to true. If the TargetID is 1 (this is the waypoint on the right), we want to flip the sprite on the X to false.

The Moss Giant enemy movement is setup for movement and we are ready to setup a few more. Until next time, cheers!

--

--

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