'problems with enemy melee
I've been working on a 2d game for weeks and nothing works. I'm not the best coder out there I'm still learning! In my game I have a player and then an enemy. I need the enemy to behave by itself so I've been following many youtube tutorials, however, it seems that all of them have some sort of problem. I have checked for spelling and everything but still no result. I followed this tutorial (https://www.youtube.com/watch?v=waj6i9cQ6rM) lately but it doesn't work for me. My enemy just plays the attack animation over and over when the player is not even close and it doesn't move from its position.
This is my code:
void EnemyLogic()
{
distance = Vector2.Distance(transform.position, target.transform.position);
if(distance > attackDistance)
{
Move();
StopAttack();
}
else if (attackDistance >= distance && cooling == false)
{
Attack();
}
if (cooling)
{
Cooldown();
Animator.SetBool("Attack", false);
}
}
void Move()
{
Animator.SetBool("canWalk", false);
if(!Animator.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; // reset time when player is in rnge
attackMode = true; // check if enemy can still attack or not
Animator.SetBool("canWalk", false);
Animator.SetBool("attack", true);
//Player.GetComponent<HeroKnight>()?.TakeDamage(attackDamage);
}
void Cooldown()
{
timer -= Time.deltaTime;
if(timer <= 0 && cooling && attackMode)
{
cooling = false;
timer = intTimer;
}
}
void StopAttack()
{
cooling = false;
attackMode = false;
Animator.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 );
}
}
public void TriggerCooling()
{
cooling = true;
}
Solution 1:[1]
You have written a condition here that does not allow movement to occur. Eliminate this condition and limit the enemy logic to distances only.
if (!Animator.GetCurrentAnimatorStateInfo(0).IsName("LightBandit_Attack"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KiynL |
