I'm making a combat-type game I want to play a certain animation when a player is hit for a certain amount, yet I can't find a way to measure the damage a humanoid takes at a time.
local humanoid = script.Parent.Humanoid local fatal_hit = Instance.new("Animation") fatal_hit.AnimationId = 'rbxassetid://xxxxxxxx' fatalTrack = script.Parent.Humanoid:LoadAnimation(fatal_hit) humanoid.Parent.Health:Destroy() humanoid.HealthChanged:Connect(function(health) local DMG = health - humanoid.MaxHealth if DMG >= 70 end)
This obviously won't work, as DMG is just the difference between the health and maxHealth, and will play whenever the health is below 30. Any help would be greatly appreciated. And for some reason, my typing is interpreted as a code block? Not sure how to fix it...
So basically to solve this problem we are going to make a variable called "damageTook" My theory is that everytime the event HealthChanged executes it will add the parameter "health" and "damageTook" together.
Next were gonna say "if damageTook greater than 70 then" Don't need to make too much changes :)
"damageTook" should be a global variable instead of local, since when the player dies he can have his "damageTook" resetted to 0.
Here is your script hopefully fixed:
local humanoid = script.Parent.Humanoid local fatal_hit = Instance.new("Animation") fatal_hit.AnimationId = 'rbxassetid://xxxxxxxx' fatalTrack = script.Parent.Humanoid:LoadAnimation(fatal_hit) humanoid.Parent.Health:Destroy() local damageTook = 0 humanoid.HealthChanged:Connect(function(health) damageTook = damageTook + health if damageTook <= 70 then -- // play animation end end)
You can ask me clarification anytime :)
The formula for doing this is:
local damageTaken = originalHealth - newHealth
You would set a health variable before the function, such as:
local health = humanoid.Health
Here is an example of a function that prints said health:
local hum = script.Parent.Humanoid local health = hum.Health -- Most important variable hum.HealthChanged:Connect(function(newHealth) local damageTaken = health - newHealth print(damageTaken) health = newHealth -- This line doesn't actually set the health, and this is done on purpose so the Humanoid's health doesn't change, but the value of the variable does end)
If you actually added 0 to the new amount of health (as the other answer mentioned), that is not the damage taken. That is the new amount of health. Therefore, you subtract the new health from the original health (if the original health was 100 and the new health is 80, the damage taken is 20).
As a precaution, this function could also be added to reset the value of the variable:
hum.Died:Connect(function() health = hum.MaxHealth end)