How would I detect if the player can see an object?

I’m trying to make a gun system and I want to detect if the player can see another player/object. How would I do this? Any help would be very appreciated! :smile:

15 Likes

You can just raycast to the object from the player’s head. If the ray returns a part on the object you want to check if the player can see. Then the player can see the object. However if another part is returned, or no part is returned. The player cannot see the object.

The Method of the Solution


You should utilize raycasting and camera methods. Raycasting ensures that from player’s view, they can see the object or not if there are obstructing objects.

Raycasting is recommended, you should start the ray from the head towards the lookVector. Whenever the ray hits something, do something. The ray should also be cast on the mouse’s position if you’re looking for direct sight.

For indirect vision, camera methods and some magic with raycasting should do the trick.

3 Likes

I mean if you’re gonna add the bit about the “towards” the lookVector… I’d definitely like to see the math behind this if you can provide. I know theirs two params, Origin, Target. If the Origin is the head of the character, And you want to raycast towards the lookVector but still raycast to the target How would the “Target” param look in this situation?

Head.CFrame.lookVector * maxDistance.

Would this answer the question for you?

Ahh I guess that’s an explicit type. That would literally only find what’s directly in front of you within what ever distance you set. I had line of sight in mind when answering this question. But yeah there’s more than enough information here @TheFuzi if you still need help getting started you can check the developer hub.

https://developer.roblox.com/articles/Raycasting

That’s why I pointed out three types:

  • Directly infront of the head
  • Directly at the mouse
  • Indirectly from the viewport – which I’m really fuzzy about
1 Like

Alternate Solution:


The solutions posted above are good and usable, but here is an alternative one.

1.Use Region3 to create a box infront of the player’s character
2.Detect if any players are within the Region3

1 Like

WorldToScreenPoint already returns a boolean indicating whether the Vector3 point is within the bounds of the screen. Do that as a first test, if it’s false you should not raycast as raycasting is quite expensive. If the player is in the screen proceed to raycast to detect if the player is occluded by an object.

4 Likes

WorldToScreenPoint is the best solution.

e.g.

local _, withinScreenBounds = Camera:WorldToScreenPoint(part.Position)

if withinScreenBounds then
   -- We have successfully detected if the player can see the part.
end
60 Likes

now the only problem is if the part was really big and to know if the part was on the screen