Make enemy not see through walls

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ras0922$$

I am currently making a top down shooter and want my enemy to not see through walls.
I am using Area2D to detect the player. The walls are static body.

:bust_in_silhouette: Reply From: Magso

You can use a Raycast2D, use get_collider() to get the first object it hits and check if that object is the player.

But Raycast2D is for one direction only while using Area2D the enemy is able to look 360 degree.So I used Area2D.

Ras0922$$ | 2020-07-17 16:45

In that case use both. Detect the player with the area then set the raycast cast_to to the player’s position, that will then detect if there’s a wall in the way.

Magso | 2020-07-17 17:00

can you give me an example of the code?

Ras0922$$ | 2020-07-17 18:16

Like this

func on_area_body_entered(body):
    raycast.cast_to = player.global_postion-raycast.global_position #cast_to is local to the raycast node
    raycast.enabled = true
    if raycast.is_colliding() && raycast.get_collider() == player:
        #can see player

Magso | 2020-07-18 01:16

Raycast is returning false for is colliding even though cast to is at player position(local to Enemy/RayCast)

Ras0922$$ | 2020-07-18 07:37

What do I put under the if statement?

WhenGamingKalieds | 2020-09-22 14:57

Ras0922$$ already had an area signal with that functionality in it, so it depends on how your game’s set up, here’s a very simple example using look_at.

if raycast.is_colliding() && raycast.get_collider() == player:

Magso | 2020-09-22 17:16