More efficient way to do knockdown animation?

I have a code that plays a knockdown when you get below 10 health. Also it makes you able to be picked by another player by pressing K. The code works, but it’s finicky, wondering if there was a more efficient way to do this?

I know repeat loops are pretty horrific sometimes, is there something I can replace them with?

game.Players.PlayerAdded:Connect(function(player)
 
	player.CharacterAdded:Connect(function()
 
		repeat wait() until player.Character
		local Character = player.Character
 
 

		local track = Instance.new("Animation")
		track.AnimationId = "rbxassetid://6845922693"
		local anim = Character.Humanoid:LoadAnimation(track)
 
 
		local track2 = Instance.new("Animation")
		track2.AnimationId = "rbxassetid://6845883493"
		local anim2 = Character.Humanoid:LoadAnimation(track2)
 
		print(Character.Name)
 
		while true do
			wait(0.5)
			repeat wait(0.5) 
			until Character.Humanoid.Health <= 10
 
			local knocked = Instance.new("BoolValue")
			knocked.Name = "Knocked"
			knocked.Parent = Character
			game.Debris:AddItem(knocked,20)
 
			local hit = Instance.new("BoolValue")
			hit.Name = "Hit"
			hit.Parent = Character
			game.Debris:AddItem(hit,20)
 
 
			anim:Play()
			anim2:Play()
 
			Character.HumanoidRootPart.Anchored = true
			wait(20)
			if anim2 then
				anim2:Stop()
				Character.HumanoidRootPart.Anchored = false
 
			end
		end
	end)
end)

Any help is appreciated, thanks!

1 Like

I use a custom damage module instead of the base :TakeDamage, this means I don’t have to worry about base damage because there’s no good way to stop damage from killing you at 0 hp. In this, I also check if they should be stunned or knocked down or if they are already knocked down. I suggest using something like this as well.

1 Like

I think you could use

Character:WaitForChild("Humanoid").HealthChanged:Connect(function(newHealth)

     if newHealth <= 10 then

        --do stuff
    end
end)

https://developer.roblox.com/en-us/api-reference/event/Humanoid/HealthChanged

2 Likes

instead of using Character.Humanoid:LoadAnimation (depricated) try to use Character.Humanoid:FindFirstChildOfClass("Animator")

2 Likes

You have redundant code and it is not advisable to use wait()
You could just do this instead

player.CharacterAdded:Connect(function(Character)

Character is a passed argument of CharacterAdded
Its the same as Player is a passed argument of PlayerAdded