- Home /
2D Obstacle Avoiding Enemies In 2D - TopDown Dungeon Help
Hey everyone,
I'm currently making a top-down dungeon crawler where enemies chase after the player, but there are obstacles around the room that they get stuck on when following their path to the player.
I've tried to use ray casts and make them decide between moving left or right to avoid obstacles, but that doesn't seem to be the perfect solution and multiple enemies get stuck on each other or get stuck in a continuous dodge loop where they keep detecting each other.
These guys here are getting stuck (highlighted in red). I was wondering if anyone had any ideas of methods to get around this?
Well you should raycast forward of the enemies to see if the can locate the player visually, then if not, deter$$anonymous$$e if the player is left or right of the enemies current position with something like
public static float AngleDir(Vector2 A, Vector2 B)
{
return -A.x * B.y + A.y * B.x;
}
then raycast in the corresponding direction only the relative horizontal distance, and move towards that direction if unobstructed, finally if that path is obstructed raycast towards the right and see if it is unobstructed, if that is, raycast behind and move backwards, then restart the process. But to save resources, only attempt pathfinding once the enemy has reached its current assigned destination, UNLESS that destination is the player. IE player is visible. The big thing and what most people do is create a visibility function that checks if the player is visible, and if so, sets the visibility to true. For example, if the enemy is facing away from the player, and you use a function to deter$$anonymous$$e the players angle is out of the visual angle of the enemy, you can immediately return visibility as false without ever raycasting.
An alternative would be to create a 2D grid system and half Walkable and Non-Walkable tagged sections. like 0 means walkable, 1 means non-walkable
[1][1][1][1][1][1]
[1][0][0][0][0][1]
[1][0][0][1][0][1]
[1][0][1][0][0][1]
[1][0][0][0][0][1]
[1][1][1][1][1][1]
Then check if player is in front, left, right, or behind, and check nodes nearest to enemy for greatest direction, if obstructed move to second greatest direction, then if all else, check opposite direction by 1 and reattempt movement. The only issue here is that enemies won't avoid eachother unless you create an enemy grid as well.
Your answer
