I’ve been trying to make a fall damage script that’s based on distance fallen, but I keep having problems with the script not calculating a player’s distance fallen correctly. The number printed by line 31 often ranges from 0.38 to 2.77.
I have tried using RunService.RenderStepped
to replace the wait()
on line 20, but I couldn’t figure out how. Saving script.Parent.HumanoidRootPart.Position.Y
as a variable didn’t work, either.
Here is the full code:
local BeginFallingY = nil
local StoppedFallingY = nil
local SafeFallDistance = 20 --// How far can one fall before taking damage
local DamagePerStud = 0.8 --// For every stud fallen, this much damage is inflicted
local Sound = script.DeathSound
Sound.Parent = script.Parent.HumanoidRootPart
script.Parent.Humanoid.StateChanged:Connect(function(old,new)
if new == Enum.HumanoidStateType.Freefall then
--// Start tracking their falling
BeginFallingY = script.Parent.HumanoidRootPart.Position.Y
--// See if the highest point of someone's fall changes
repeat
if script.Parent.HumanoidRootPart.Position.Y > BeginFallingY then
BeginFallingY = script.Parent.HumanoidRootPart.Position.Y
print("start height increased")
end
wait()
until script.Parent.Humanoid:GetState() ~= Enum.HumanoidStateType.Freefall
elseif old == Enum.HumanoidStateType.Freefall or new == Enum.HumanoidStateType.FallingDown then
--// Check if player landed in water or started flying
if new == Enum.HumanoidStateType.Swimming or new == Enum.HumanoidStateType.PlatformStanding then
BeginFallingY = nil
return
end
StoppedFallingY = script.Parent.HumanoidRootPart.Position.Y
--// Calculates distance fallen.
local DistanceFell = BeginFallingY - StoppedFallingY
print("Distance fallen: " .. tostring(DistanceFell) .. " studs")
--// Check if distance fallen is more than SafeFallDistance
if DistanceFell >= SafeFallDistance then
local DangerDistance = DistanceFell - SafeFallDistance
--// Evalute player health
if (DangerDistance * DamagePerStud) >= script.Parent.Humanoid.Health then
Sound:Play()
script.Parent.Humanoid.Health = 0
else script.Parent.Humanoid:TakeDamage(DistanceFell * DamagePerStud)
end
end
--// Cleanup
BeginFallingY = nil
StoppedFallingY = nil
end
end)
Any ideas on how to resolve this issue? All help is appreciated.