How can I clamp the players health so it does not go over their maxHealth value. I have a tool that increases the players health by 35 on use. If the players current health is on 90 for instance and then they go by using the tool, their health will increase to 125. How could I stop this from happening, here is my code that uses Humanoid:TakeDamage:
local biteEvent = script.Parent.BiteTaken
local finishedEvent = script.Parent.AppleFinished
local configs = require(script.Parent.Configurations)
biteEvent.OnServerEvent:Connect(function(player)
player.Character.Humanoid:TakeDamage(-configs.appleHealthRegen)
end)
finishedEvent.OnServerEvent:Connect(function()
script.Parent:Destroy()
end)
local finishedEvent = script.Parent.AppleFinished
local configs = require(script.Parent.Configurations)
biteEvent.OnServerEvent:Connect(function(player)
local humanoid = player.Character and player.Character:FindFirstChild("Humanoid")
if humanoid then
local currentHealth = humanoid.Health
local maxHealth = humanoid.MaxHealth
local newHealth = currentHealth + configs.appleHealthRegen
-- Calculate the maximum health the player's health can be after using the tool
local maxPossibleHealth = math.min(maxHealth, newHealth)
-- Update the player's health to the lower of calculated maximum health and their actual current health
humanoid.Health = maxPossibleHealth
end
end)
finishedEvent.OnServerEvent:Connect(function()
script.Parent:Destroy()
end)
you should manually set the health instead of using Humanoid:TakeDamage with a negative value.
local biteEvent = script.Parent.BiteTaken
local finishedEvent = script.Parent.AppleFinished
local configs = require(script.Parent.Configurations)
biteEvent.OnServerEvent:Connect(function(player)
local humanoid = player.Character.Humanoid
-- Calculate the new health after regeneration
local newHealth = humanoid.Health + configs.appleHealthRegen
-- Clamp the new health so it doesn't exceed MaxHealth
humanoid.Health = math.min(newHealth, humanoid.MaxHealth)
end)
finishedEvent.OnServerEvent:Connect(function()
script.Parent:Destroy()
end)
That did not seem to work, it didn’t even heal the player at all. I just have a server script inside of the healing tool and a local script. The code you provided is inside of the serverscript and is triggered by a remote event. Also I delete the module script inside of the tool. So I changed up the server script a bit:
local biteEvent = script.Parent.BiteTaken
local finishedEvent = script.Parent.AppleFinished
biteEvent.OnServerEvent:Connect(function(player)
local humanoid = player.Character.Humanoid
-- Calculate the new health after regeneration
local newHealth = humanoid.Health + 25
-- Clamp the new health so it doesn't exceed MaxHealth
humanoid.Health = math.min(newHealth, humanoid.MaxHealth)
end)
finishedEvent.OnServerEvent:Connect(function()
script.Parent:Destroy()
end)