#check if enemy has line of sight to player
21 messages · Page 1 of 1 (latest)
I think most people would do this is with a raycast https://docs.godotengine.org/en/stable/tutorials/physics/ray-casting.html
Introduction: One of the most common tasks in game development is casting a ray (or custom shaped object) and checking what it hits. This enables complex behaviors, AI, etc. to take place. This tut...
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
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)
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
how do i actually check if it hits the player?
Result is equal to true or false
Which tells you if it can see the player or not
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
Also, note this section https://docs.godotengine.org/en/stable/tutorials/physics/ray-casting.html#collision-exceptions
Introduction: One of the most common tasks in game development is casting a ray (or custom shaped object) and checking what it hits. This enables complex behaviors, AI, etc. to take place. This tut...