# What would you use to detect when a player is under water?

I know that there’s `FloorMaterial`, however I want to know how to detect once the full body of the player is underwater.

Small example: https://gyazo.com/428ac41246af0ae6979ded4eb8de36d0

I currently don’t have any code, as I purely don’t know how to achieve this, any suggestions are appreciated.

1 Like

You can use a ray to detect it. I gave some sample code below that should work. That being said, you may need to adjust the ray as I did a y value of -5 but im not sure if that’s the best.

``````local WRay= Ray.new(Player.Character.Head.Position,Player.Character.Head.CFrame:vectorToWorldSpace(Vector3.new(0, -5, 0)) -- You may need to adjust how far to cast this. I just did 5 as a standard. I used the head as that is usually last submerged when going straight down.
local hit, position, normal, material = workspace:FindPartOnRay(WRay,Player.Character)
if material == Enum.Material.Water then
--Player is in water
end
``````
6 Likes

You can use a Region3, extended to the entire space the water takes up which should be a few studs below the surface of the water. You should check if all of their body parts are in the Region3 to declare that that the player is fully immersed in the water

2 Likes

Here’s a little issue you would have with this code: when the player moves in the water, they will be titled or “angled” towards the direction they’re moving to, meaning their head will be closer to the water, like the head is face-planting, and casting a day downwards wouldn’t really help determine if the player is fully immersed

That’s fair. You could always have it check the orientation of the player model and cast the ray directly downward on the Y axis, but your method also works. Cheers!

Question: what happens if you aren’t using a flat body of water and need to detect if a player is immersed over arbitrary spaces of water around the map?

For example, this would be easy to work with if you just had a flat layer of water, but what goes for hills with rivers, waterfalls, ponds and other elevated bodies of water? Not just position, but size as well: what would I do for a rounded body, triangular body or any other shape? Region3 casts over an unrotated quadrilateral space so it wouldn’t have the same accuracy.

Do you have any other suggestions for checking a player being under water? I remember answering a question like this before but my answer wasn’t the best, it was just checking for state. Truthfully I’ve been trying out a few methods like raycasting and all but they don’t seem practical.

2 Likes