I am trying to make a 2D enemy, and what should happen when the player enters the trigger area? The enemy walks forward and attacks. The problem is that the enemy is floating in the air. So when the player steps into the trigger area, the only animation that plays is just the idle animation.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Animator anim;
public int maxHealth = 100;
int currentHealth;
public Transform rayCast;
public LayerMask raycastMask;
public float rayCastLength;
public float attackDistance;
public float movespeed;
public float timer;
private RaycastHit2D hit;
private GameObject target;
private float distance;
private bool attackMode;
private bool inRange;
private bool cooling;
private float intTimer;
// Start is called before the first frame update
void Awake()
{
intTimer = timer;
anim = GetComponent<Animator>();
}
void OnTriggerEnter2D(Collider2D trig)
{
if(trig.gameObject.tag == "Player")
{
target = trig.gameObject;
inRange = true;
}
}
void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
Debug.Log("Enemy Hit");
anim.SetTrigger("Hurt");
if (currentHealth <= 0)
{
Die();
}
}
void Die()
{
Debug.Log("Enemy died");
anim.SetBool("Die", true);
gameObject.layer = LayerMask.NameToLayer("Dead Enemies");
GetComponent<Collider2D>().enabled = true;
this.enabled = false;
}
// Update is called once per frame
void Update()
{
if (inRange)
{
hit = Physics2D.Raycast(rayCast.position, Vector2.left, rayCastLength, raycastMask);
RaycastDebugger();
}
if(hit.collider != null)
{
EnemyLogic();
}
else if(hit.collider == null)
{
inRange = false;
}
if(inRange == false)
{
anim.SetBool("Can Walk", false);
StopAttack();
}
}
void EnemyLogic()
{
distance = Vector2.Distance(transform.position, target.transform.position);
if(distance > attackDistance)
{
Move();
StopAttack();
}
else if(attackDistance >= distance && cooling == false)
{
Attack();
}
if (cooling)
{
anim.SetBool("Attack", false);
}
}
void Move()
{
anim.SetBool("Can Walk", true);
if(!anim.GetCurrentAnimatorStateInfo(0).IsName("LightBandit_attack"))
{
Vector2 targetPosition = new Vector2(target.transform.position.x, transform.position.y);
transform.position = Vector2.MoveTowards(transform.position, targetPosition, movespeed * Time.deltaTime);
}
}
void Attack()
{
timer = intTimer;
attackMode = true;
anim.SetBool("Can Walk", false);
anim.SetBool("Attack", true);
}
void StopAttack()
{
cooling = false;
attackMode = false;
anim.SetBool("Attack", false);
}
void RaycastDebugger()
{
if(distance > attackDistance)
{
Debug.DrawRay(rayCast.position, Vector2.left * rayCastLength, Color.red);
}
else if(attackDistance > distance)
{
Debug.DrawRay(rayCast.position, Vector2.left * rayCastLength, Color.green);
}
}
}