Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 1 year ago
Edited 1 year ago

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

Log in to vote
0
Answered by
NykoVania 231 Moderation Voter
1 year ago
Edited 1 year ago

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)
Ad

Answer this question