Making a corpse system

I want to design a corpse system. In this system, whenever a player dies their body needs to be like a ragdoll. So far, the system has very strange and varying results, which is confusing.

Sometimes, the body will fall as expected, however most of the time it will end up standing up, without falling. Rarely, it even enters a sort of ragdoll state, where the character is doing the ragdolled animation (the one that kinda looks like walking in slow motion), despite the humanoid being dead.

Any idea how to fix this? Here is the code I use:

function module:SetUpRagdoll(char)
	for _, joint : Motor6D in pairs(char:GetDescendants()) do
		if joint:IsA("Motor6D") then
			local socket = Instance.new("BallSocketConstraint")
			local a0 = Instance.new("Attachment")
			local a1 = Instance.new("Attachment")

			socket.Enabled = false

			a0.Parent = char.HumanoidRootPart
			a1.Parent = joint.Part1

			socket.Parent = joint.Parent
			socket.Name = "RagdollJoint"

			socket.Attachment0 = a0
			socket.Attachment1 = a1

			a0.CFrame = joint.C0
			a1.CFrame = joint.C1

			socket.LimitsEnabled = true
			socket.TwistLimitsEnabled = true
		end
	end
end

function module:Ragdoll(char : Model)
	if char:GetAttribute("Ragdolled") == true then return end
	char:SetAttribute("Ragdolled", true)
	
	char.PrimaryPart:SetNetworkOwner(nil)
	char.Humanoid:ChangeState(Enum.HumanoidStateType.Dead)
	char.Humanoid.PlatformStand = true

	for _, joint in pairs(char:GetDescendants()) do
		if joint:IsA("BallSocketConstraint") then
			joint.Enabled = true
		elseif joint:IsA("Motor6D") then
			joint:Destroy()
		elseif joint:IsA("BasePart") then
			joint.CanCollide = true
			joint.Anchored = false
		elseif joint:IsA("Script") or joint:IsA("LocalScript") then
			joint:Destroy()
		end
	end
end

How it works is:

  1. Once the character has spawned, call module:SetupRagdoll(character)
  2. Once the humanoid has died, call module:Ragdoll(character)

When the ragdoll effect happens, the player stays standing since there isn’t enough force to make them fall. This mostly occurs when the player isn’t moving because there’s no momentum to make them fall over.

You can use ApplyImpulse to apply force to the players PrimaryPart to prevent this from happening.

char.PrimaryPart:ApplyImpulse((char.PrimaryPart.CFrame.LookVector * 100) * char.PrimaryPart.AssemblyMass)

(↑Put this in the ragdoll function)