Search code examples
unity-game-enginedirectionanimator

Enemy 3d Follow Player - play animation in function of direction unity 3d?


I am currently working on a 2.5d game. I have sprites in a 3d space. It is a kind of football game. I want that when an enemy follows my player that he plays an animation depending on the direction he is going.

I used the transform.position.x method but that does not work well because there is no input. I would like to know how to play an animation where the enemy runs from behind when he is going backwards, from right when he is going right, left when he is going left, back-left when he is moving from back to left. Without going through the blend tree if possible.

My code :

using UnityEngine;

public class EnnemyAnimation : MonoBehaviour
{
    void Update()
    {
       if (transform.position.x > 0)
       {
           Debug.Log("right");   // play animation right
       }
       else if (transform.position.x < 0)
       {
           Debug.Log("left");    // play animation left
       }
       else if (transform.position.z < 0) 
       {
           Debug.Log("back");    // play animation back
       }
       else if (transform.position.z > 0)
       {
           Debug.Log("front");    // play animation front
       }
       else if (transform.position.x < 0 && transform.position.z < 0)
       {
           Debug.Log("back-left");    // play animation back left
       }
       else if (transform.position.x > 0 && transform.position.z < 0)
       {
           Debug.Log("back-right");   // play animation back right
       }
       else if (transform.position.x < 0 && transform.position.z > 0)
       {
           Debug.Log("front-left");    // play animation front left
       }
       else if (transform.position.x > 0 && transform.position.z > 0)
       {
           Debug.Log("front-right");   // play animation front right
       }
    }
}

Solution

  • Since your enemies are following the player, you can find which direction they are going by substracting Player's position from Enemy's position. Then you can decide which animation to play just like you did on your if-else statements.

    Vector2 facingDirection = new Vector2(player.transform.position.x - enemy.transform.position.x,
         player.transform.position.z - enemy.transform.position.z);
    
    if(facingDirection.x > 0 && facingDirection.y > 0) {
       ...
    }
    if else(facingDirection.x < 0 && facingDirection.y) {
       ...
    }
    ...
    

    We used transform.x and transform.z of player and enemy because your game is in 3d world and we dont want to go up (y axis is up).

    If you didnt understood why we substracted positions I recommend you this video

    https://www.youtube.com/watch?v=sYf4bSj9j2w