I am making a roguelike in unity 2d and my I use the Astar Pathfinding Project for my enemies. I have an enemky that does a melee attack. This means that it doesn´t just stop at the same position as the player. It stops on the player´s left or right side, depending on the direction the enemy was, and then starts its melee attack at the player. For doing this, I have 2 empty objects on both sides of the player, and a code that changes the pathfinding AI Destination Setter depending on the velocity o0f the enemy. When I had capsules as objects it worked just fine, but now that I implemented sprites my enemy has multiple errors, such as changing every frame its destination like crazy when it reaches the player position, being unable to decide which path to choose. Is there a way I can do this easily, since melee enemies are a really common things in videogames and I am really new in this field?
If possible, I would also like to know how to modify the components so that my enemy doesn´t start attacking only when it reached its position, since this means that the player can´t be hurt if it doesn´t stop moving. I want the enemies to take into account a larger space around the player to enter “attack mode”.
I tried the following code, being enemyPos1 and enemyPos2 the 2 empty objects around the player.
void Update()
{
if (aiPath.desiredVelocity.x >= 0.01f)
{
transform.localScale = new Vector3(1, 1, 1);
aiDestinationSetter.target = enemyPos1;
} else if (aiPath.desiredVelocity.x <= -0.01f)
{
transform.localScale = new Vector3(-1, 1, 1);
aiDestinationSetter.target = enemyPos2;
}
//Atacar
if (Vector2.Distance((Vector2)attackPoint.position, (Vector2)playerTransform.position) < attackRange && aiPath.desiredVelocity.x == 0 && aiPath.desiredVelocity.y == 0)
{
if (canAttack == true)
{
StartCoroutine(Atacar());
}
}
//Muerte
if (hp <= 0)
{
Destroy(this.gameObject);
}
}