Zombie legs still moving after it dies and ragdolls

Im tryna make a zombie ragdoll system and everything works fine except for the ragdolls for some reason the zombie is still walking during ragdoll i generated it using chatgpt and for some reason even tho i made sure to return end when it dies it still tries walking…


heres the code:

-- FULL R6 ZOMBIE AI — improved ragdoll on death
-- Features:
-- • BreakJointsOnDeath = false
-- • Converts Motor6D to BallSocketConstraints using original joint location.
-- • Strong, long outward impulse on limbs for "defeated" spread.
-- • BallSocketConstraints for physics ragdoll (pushable by players).
-- • Fling effect upon death.
-- • AI is immediately terminated upon death (stops walking/jumping/physics).
-- • Auto-death for testing.

local zombie = script.Parent
assert(zombie and zombie:IsA("Model"), "Parent must be a Model (zombie)")

local humanoid = zombie:WaitForChild("Humanoid")
local hrp = zombie:WaitForChild("HumanoidRootPart")

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local PathfindingService = game:GetService("PathfindingService")
local Debris = game:GetService("Debris")

-- CONFIG
local MOVING = true
local MOVE_SPEED = 13
local DAMAGE = 8
local ATTACK_RANGE = 4
local ATTACK_COOLDOWN = 1
local DETECTION_RADIUS = 50
local AUTO_DIE_TIME = 5 	 	 	 -- auto death for testing
local LIMB_MAX_ANGLE = 100 	 	 -- how floppy limbs are
local DEATH_FLING_FORCE = Vector3.new(0, 20, 0) -- Softer upward fling force (WAS 40)
local LIMB_SEPARATION_FORCE = 80 -- Strong push limbs outward initially (Increased for dramatic spread)
local LIMB_SEPARATION_DURATION = 0.2 -- Time to apply initial push (Increased slightly)

-- ensure joints aren't automatically destroyed by Roblox
humanoid.BreakJointsOnDeath = false

-- animator & animation
local animator = humanoid:FindFirstChildWhichIsA("Animator")
if not animator then
	animator = Instance.new("Animator")
	animator.Parent = humanoid
end

local attackAnim = Instance.new("Animation")
attackAnim.AnimationId = "rbxassetid://119801350765470"
local attackTrack = animator:LoadAnimation(attackAnim)
humanoid.WalkSpeed = MOVE_SPEED
local lastAttack = 0
local isDead = false -- NEW: Flag to stop AI loop immediately

-- auto kill after AUTO_DIE_TIME for testing
task.delay(AUTO_DIE_TIME, function()
	if humanoid and humanoid.Health > 0 then
		humanoid:TakeDamage(humanoid.MaxHealth)
	end
end)

-- helper: nearest player
local function getNearestPlayer()
	if not MOVING then return end
	local nearest, bestDist = nil, math.huge
	for _, p in ipairs(Players:GetPlayers()) do
		local c = p.Character
		if c and c:FindFirstChild("HumanoidRootPart") and c:FindFirstChildWhichIsA("Humanoid") then
			local dist = (c.HumanoidRootPart.Position - hrp.Position).Magnitude
			if dist < bestDist and dist <= DETECTION_RADIUS then
				bestDist = dist
				nearest = c
			end
		end
	end
	return nearest
end

-- attack logic
local function tryAttack(target)
	if not target then return end
	if not MOVING then return end
	local now = tick()
	if now - lastAttack < ATTACK_COOLDOWN then return end
	local targetHRP = target:FindFirstChild("HumanoidRootPart")
	local targetHum = target:FindFirstChildWhichIsA("Humanoid")
	if not targetHRP or not targetHum then return end

	if (targetHRP.Position - hrp.Position).Magnitude <= ATTACK_RANGE then
		targetHum:TakeDamage(DAMAGE)
		pcall(function()
			if attackTrack.IsPlaying then attackTrack:Stop() end
			attackTrack:Play()
		end)
		lastAttack = now
	end
end

-- simple movement (pathfinding waypoints)
local function chase(target)
	if not MOVING then return end
	if not target or not target:FindFirstChild("HumanoidRootPart") then return end
	local targetPos = target.HumanoidRootPart.Position
	local path = PathfindingService:CreatePath()
	path:ComputeAsync(hrp.Position, targetPos)
	if path.Status ~= Enum.PathStatus.Success then
		-- Fallback to simple MoveTo if pathfinding fails
		humanoid:MoveTo(targetPos)
		return
	end
	local wps = path:GetWaypoints()
	for _, wp in ipairs(wps) do
		if humanoid.Health <= 0 or isDead then return end -- Check isDead in loop
		humanoid:MoveTo(wp.Position)
		humanoid.MoveToFinished:Wait(0.2)
		tryAttack(target)
		task.wait(0.03)
	end
end

-------------------------------
-- RAGDOLL LOGIC: Motor6D to BallSocket conversion
-------------------------------

-- Converts an existing Motor6D joint into a BallSocketConstraint (BSC)
local function convertMotorToBallSocket(motor)
	local part0 = motor.Part0
	local part1 = motor.Part1
	if not part0 or not part1 or not motor.Parent or not motor.Name then return end

	-- 1. Create Attachments using Motor6D C0/C1 to preserve the exact joint location
	-- This ensures the pivot point is at the seam between the parts, not inside them.
	local a0 = Instance.new("Attachment")
	a0.Name = motor.Name .. "A0"
	a0.CFrame = motor.C0 -- Relative position to Part0
	a0.Parent = part0

	local a1 = Instance.new("Attachment")
	a1.Name = motor.Name .. "A1"
	a1.CFrame = motor.C1 -- Relative position to Part1
	a1.Parent = part1

	-- 2. Create the BallSocketConstraint
	local bsc = Instance.new("BallSocketConstraint")
	bsc.Name = motor.Name .. "_BSC"
	bsc.Attachment0 = a0
	bsc.Attachment1 = a1
	bsc.LimitsEnabled = true
	bsc.UpperAngle = LIMB_MAX_ANGLE
	bsc.TwistLimitsEnabled = true
	bsc.TwistLowerAngle = -LIMB_MAX_ANGLE
	bsc.TwistUpperAngle = LIMB_MAX_ANGLE
	bsc.MaxForce = math.huge -- FIX: Makes the joints virtually unbreakable by physics
	bsc.Parent = part0

	-- 3. Destroy the original Motor6D
	motor:Destroy()
end

-- Activates the full physics ragdoll state
local function activateRagdoll(model)
	if not model or not model:IsA("Model") then return end

	local h = model:FindFirstChildWhichIsA("Humanoid")
	if h then
		h.BreakJointsOnDeath = false
		h.PlatformStand = true -- Keep the humanoid from trying to stand up
		h.WalkSpeed = 0 -- FIX: Stop movement immediately
		h.JumpPower = 0 -- NEW: Disable jumping
		h:MoveTo(model:GetPrimaryPartCFrame().Position) -- FIX: Cancel current MoveTo command
		pcall(function() h:ChangeState(Enum.HumanoidStateType.Dead) end) -- NEW: Explicitly set to Dead state
	end

	local hrpPart = model:FindFirstChild("HumanoidRootPart")
	local torso = model:FindFirstChild("Torso") or model:FindFirstChild("UpperTorso")

	-- 1. Convert all existing Motor6D joints to BallSocketConstraints
	-- and destroy any remaining static joints (Welds)
	for _, child in ipairs(model:GetDescendants()) do
		if child:IsA("Motor6D") then
			convertMotorToBallSocket(child)
		elseif child:IsA("Weld") or child:IsA("WeldConstraint") then
			pcall(function() child:Destroy() end)
		end
	end

	-- 2. Prepare parts for physics simulation and temporarily disable collisions
	for _, p in ipairs(model:GetChildren()) do
		if p:IsA("BasePart") then
			p.Anchored = false
			p.Massless = false
			-- Small damping for less jittery physics
			p.CustomPhysicalProperties = PhysicalProperties.new(1, 0.5, 0.15)
			p.CanCollide = false -- Temporarily disable collisions for separation push
		end
	end

	-- 3. Apply outward limb separation impulse (to prevent clipping and spread limbs)
	if torso then
		for _, limb in ipairs(model:GetChildren()) do
			-- Target limbs (all parts that aren't the torso/hrp/head)
			if limb:IsA("BasePart") and limb ~= torso and limb ~= hrpPart and limb.Name ~= "Head" then
				local dir = (limb.Position - torso.Position)
				-- If parts are perfectly centered (e.g., initial spawn state), give a random outward push
				if dir.Magnitude < 0.5 then
					dir = Vector3.new(math.random(-5, 5), math.random(2, 6), math.random(-5, 5))
				end
				dir = dir.Unit

				local limbBV = Instance.new("BodyVelocity")
				-- Increased upward bias for more dramatic spread
				limbBV.Velocity = dir * LIMB_SEPARATION_FORCE + Vector3.new(0, 15, 0)
				limbBV.MaxForce = Vector3.new(1e5, 1e5, 1e5)
				limbBV.Parent = limb
				Debris:AddItem(limbBV, LIMB_SEPARATION_DURATION)
			end
		end
	end

	-- 4. Apply small upward fling impulse to the HRP
	if hrpPart and hrpPart:IsA("BasePart") then
		local bv = Instance.new("BodyVelocity")
		bv.MaxForce = Vector3.new(1e6, 1e6, 1e6)
		-- Fling forward/upwards (forward component reduced to 5, was 10)
		local flingDirection = hrpPart.CFrame.LookVector * 5 + DEATH_FLING_FORCE
		bv.Velocity = flingDirection
		bv.Parent = hrpPart
		Debris:AddItem(bv, 0.16)
	end

	-- 5. Re-enable collisions after separation and set Humanoid state
	task.delay(LIMB_SEPARATION_DURATION + 0.05, function()
		for _, p in ipairs(model:GetChildren()) do
			if p:IsA("BasePart") then
				p.CanCollide = true
			end
		end
		-- Final state change to Physics
		if h then pcall(function() h:ChangeState(Enum.HumanoidStateType.Physics) end) end
	end)
end


-- connect death event
humanoid.Died:Connect(function()
	MOVING = false
	isDead = true -- NEW: Set flag to stop AI loop immediately upon death
	-- small wait so the model is ready
	task.wait(0.03)
	activateRagdoll(zombie)
end)

-----------------------
-- AI Loop (chasing + attacking)
-----------------------
task.spawn(function()
	while humanoid and humanoid.Health > 0 and not isDead do -- UPDATED: Check isDead
		local target = getNearestPlayer()
		if target then
			chase(target)
			tryAttack(target)
		else
			task.wait(0.15)
		end
		task.wait(0.03)
	end
end)

Hate to be that guy but you’re better off writing the code yourself. That way you will know exactly what you wrote it to do. I’m not great with NPCs and pathfinding myself, but a bad self-made script is infinitely better than the best AI-generated one; you know how it works and how to add to/fix it.

I regret that I can’t provide a solution, but I felt obligated to tell you this anyway. I have some code I wrote from an old project that handles NPC death properly, I can send it to you if you want.

I know what its doing I understand the code I just use chatgpt because its faster than me actually typing it out myself also send the npc death code then pls but also update it so it does the ragdoll

On second thought, the code I wrote was very generalized for this purpose.

You could try this:

humanoid.Died:Connect(function()
	MOVING = false
	--isDead = true -- NEW: Set flag to stop AI loop immediately upon death
	-- small wait so the model is ready
	task.wait(0.03)
	activateRagdoll(zombie)
    script:Destroy()
end)

I commented out one of the lines so you would know what I removed, the script:Destroy() line will just completely eradicate the AI handler on death. Not sure how well this would work but it might be worth a shot.

  1. wait i think i figured out the issue

  2. when the zombie dies ill just set humanoid:MoveTo to its own position

  3. so it stops walking

Assuming MoveTo is what’s causing that leg motion. Does the NPC have a script called ‘Animate’ that dictates its animations, or are animations played from this script?

yes it has a script called Animate

ok thanks i deleted animate and it fixed it