Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to make oxygen system, but bar will start decreasing only when head is under water?

Hello, I am trying to achieve a system that will take up oxygen only when head is under water. I have GUI for that and this is made by a tutorial on YT. The oxygen starts to decrease when player is swimming, but I don't know if it's possible to do it only with head of the Humanoid.

local Slider = script.Parent.Bar.Slider
local airamount = script.Parent.Bar.AirAmount

local player = game.Players.LocalPlayer
local character = game.Players.LocalPlayer.Character
local humanoid = character:WaitForChild("Humanoid")

maxAir = 100
rnAir = maxAir
script.Parent.Bar.Size = UDim2.new(0.4,0, 0,35)


local loseAir = 0.5
local playerInWater = false

humanoid.StateChanged:Connect(function(old, new)
	
	if new == Enum.HumanoidStateType.Swimming then
		
		playerInWater = true
		
		script.Parent.Bar.Visible = true
		
	else
		
		playerInWater = false
		
		script.Parent.Bar.Visible = false
		
		rnAir = maxAir
	end
end)

while wait(loseAir) do
	

	if playerInWater == true then
		
		rnAir = math.clamp(rnAir - 1, 0, maxAir)
		
	else
		
		rnAir = math.clamp(rnAir + 1, 0, maxAir)
		
	end
	
	if rnAir < 1 then

		humanoid.Health = 0
		
    end

	local barScale = rnAir / maxAir
	
	Slider:TweenSize(UDim2.new(barScale, 0, 1, 0), "InOut", "Linear", loseAir)
	
	airamount.Text = rnAir.." / "..maxAir
	
end

1 answer

Put an invisible block in the water and detect collisions with that block.

The script below is an example.

Part.Touched:Connect(function(inst)
	if inst.Parent.Head ~= nil then
		print("Head is underwater")
	end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.