Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

[Unity] Enemy following player script

A topic by alexmmusic created Mar 24, 2021 Views: 314 Replies: 1
Viewing posts 1 to 2

Hi, I'm trying to make a game in Unity2D and I need the enemies to follow the player when they are close enoguh. For that I use an Sphere collider 2D that is the range of distance for the enemy to detect the player character. Now I need the  enemy to stop following the player character when tere is a wall between.


I thought that a good option for that was the raycasting but I have no clue how to use that for my purpose. Any idea?


Thanks a lot!

Here's a very basic solution:

I assume your following behavior already works, and that you are turning the follow behavior on when the player enters the circle collider, and off when they exit the collider.  Create an object layer just for walls and assign your wall game objects to that layer.  While the follow behavior is active (i.e. player is in range), cast a ray from the enemy's position to the player's position every 0.2 seconds or so (you don't need to do it every frame, just often enough so that it feels responsive).  Set the ray to collide with the wall layer and any other layers that should obstruct following.  If the ray returns any hits, it means line of sight to the player is blocked by the wall, so pause the follow behavior.  If there are no hits, line of sight is clear, so resume following.