- Home /
Enemy animation based on direction
Hello.
I am currently making a Maze game, where the enemies always follow a certain path determined by waypoints. I want the enemies to change their walking animation when they are facing left, right, down or up. I have set up some bools in the animator to become true, when one of the four directions of the enemy is met. By default, I have set my default transition to move left for practise. But I want the enemy direction to correspond to their position. I know that it is the transform component I need to use in my code, but I am unsure how to code it. An example would be that when the Y position is less than 0, then the MoveDown condition would be true.
Below the pictures, is the code, written so far for the enemy.
I've heard someone talking of enums. Could that be a solution?
I hope anyone can either guide me or point me to a tutorial for enemy directions for top- down games.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private Movement player;
private Animator enemyAnim;
public Transform enemyMove;
private bool MoveDown;
private bool MoveUp;
private bool MoveLeft;
private bool MoveRight;
//Array of waypoints to walk from one point to the next
[SerializeField]
Transform[] waypoints;
//Walk speed that can be set in Inspector
[SerializeField]
private float moveSpeed = 2f;
//Index of current waypoint from which Enemy walks
//To the next one
private int waypointIndex = 0;
void Start()
{
enemyAnim = GetComponent<Animator>();
enemyMove = GetComponent<Transform>();
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Movement>();
// set position of Enemy as position of the first waypoint
transform.position = waypoints[waypointIndex].transform.position;
}
private void Update()
{
Move();
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
player.Damage(1);
}
}
//Movement
private void Move()
{
transform.position = Vector2.MoveTowards(transform.position, waypoints[waypointIndex].transform.position, moveSpeed * Time.deltaTime);
if (transform.position == waypoints[waypointIndex].transform.position)
{
waypointIndex += 1;
}
if (waypointIndex == waypoints.Length)
{
waypointIndex = 0;
}
}
}
Your answer
Follow this Question
Related Questions
How can i Learn Basics of Rain AI 1 Answer
Nav Mesh Agent 0 Answers
How would I animate a 2D enemy with AI made with A*? 0 Answers