How to prevent shooting a player who is behind a wall?

Godot Version

4.3

Question

I’m remaking a very simple multiplayer top down shooter. Weapons hit a player instantly, there is no bullets, no bullets velocity etc. Just a rectangle shape for a pistol for example. If it touches a player it hits them.

What I tried is connecting Player’s hitbox collision (Area2D) “on area entered” signal, which would detect the weapon’s Area2D representing the weapon’s hitbox shape. Except this will reach a player even if it’s behind a wall.

What I’d like is the area2d to not be able to reach a player’s area2d if the player is behind a wall, but also allow a hit if the player is peeking and half of their body is out for example

Two ways that I can think of, and depending on your game, it may be a combo of both.

  1. When the weapon’s area2d intersects the wall’s area2d, stop movement in that direction.

  2. You can determine what you are going to hit if you Raycast2D from the weapon to the player. This will give you all the intersecting objects between the 2 points. Grab the first object the raycast intersects with and if it is the player, you know you have a clear path (ie: no wall in the way).

I hope this helps.

I would still want the player to be able to move their gun in walls direction, so blocking the movement isn’t going to work well for me.

Raycasts are definitely something that I looked at too, but wouldn’t I have to spawn a lot of them in multiple direction to cover the entire hitbox’s shape?

You may have to spawn multiple raycasts, depending on your game. There’s also a ShapeCast2D which I have less experience with but that may work better for you, although the docs do state that it is more computationally expensive than ray casting.

I ended up using intersect_ray() and it did the job. Thank you for the suggestions