#check if enemy has line of sight to player

21 messages · Page 1 of 1 (latest)

willow ether
#

it's pretty self explanatory (if you need more details ask me)

cloud osprey
#

If you cast a ray from the enemy to the player and the player is the only thing hit by the ray you have line of sight

willow ether
#

okie

#

ima try it

willow ether
#

hey im sorry but i could really understand the documentation, could you tell me a little bit more (sorry if im asking for too much i have only used this channel once and im nearly a complete beginner to godot)

cloud osprey
#

I'm not at my computer atm but something like this should work.

func _physics_process(delta):
    var player = $Player
    var space_state = get_world_2d().direct_space_state
    # use global coordinates, not local to node
    var query = PhysicsRayQueryParameters2D.create(global_position, player.global_position)
    var result = space_state.intersect_ray(query)
#

Then look at the value of result to see if you hit the player or not

#

Basicly you get the state of where everything is in the game, create a query of where the ray starts and ends, and then ask the state if anything intersects with the ray

#

Oh and what I wrote assumes that the enemy is checking for line of sight

willow ether
#

how do i actually check if it hits the player?

keen mauve
#

Which tells you if it can see the player or not

willow ether
#

oh

#

nope

#

result is a dictionary

#

not a bool

#

or at least i think so

cloud osprey
#

Yes the result is a dictionary of the form { position: Vector2 # point in world space for collision normal: Vector2 # normal in world space for collision collider: Object # Object collided or null (if unassociated) collider_id: ObjectID # Object it collided against rid: RID # RID it collided against shape: int # shape index of collider metadata: Variant() # metadata of collider }

#

You can look at colider, and then check if it belongs to the player