-- Piggy "Stun" Script


local debounce = false

local Gamemode = game.ReplicatedStorage.Mode

game.ReplicatedStorage.Stun.OnServerEvent:Connect(function(plr,target)
	if target then
		if target:FindFirstAncestorOfClass("Model") then
			-- Check to see if clicked model is a real player
			local piggy = target:FindFirstAncestorOfClass("Model")

			if piggy then
				if piggy:FindFirstChild("Bear") then -- Check to see if it is actually Piggy or just another contestant
					if not debounce then

						local stunTag = Instance.new("BoolValue")
						stunTag.Name = "Stunned"
						stunTag.Parent = piggy

						game.ReplicatedStorage.Announcement:FireAllClients("Piggy is gone for 20 seconds")
						piggy.Torso.Script.Disabled = true
						if piggy:FindFirstChild("UpperTorso") then
							local anim = piggy:FindFirstChild("Humanoid"):LoadAnimation(game.ReplicatedStorage.StunnedR15)
							debounce = true
							-- Freeze piggy by setting walkspeed to 0
							piggy.Humanoid.WalkSpeed = 0
							piggy.Humanoid.JumpPower = 0
							anim:Play()
							wait(20) -- wait 20 sec before enabling walkspeed again to 14 and then setting debounce to false so
							-- that the piggy can be stunned again
							anim:Stop()
							piggy.Humanoid.WalkSpeed = 14
							piggy.Humanoid.JumpPower = 20
							piggy.Torso.Script.Disabled = false
							debounce = false
						else
							local anim = piggy:FindFirstChild("Humanoid"):LoadAnimation(game.ReplicatedStorage.Stunned)
							debounce = true
							-- Freeze piggy by setting walkspeed to 0
							piggy.HumanoidRootPart.Anchored = true
							piggy.Animate.Disabled = true
							piggy.Humanoid.WalkSpeed = 0
							piggy.Humanoid.JumpPower = 0
							anim:Play()
							wait(20) -- wait 20 sec before enabling walkspeed again to 14 and then setting debounce to false so
							-- that the piggy can be stunned again
							piggy.HumanoidRootPart.Anchored = false
							piggy.Animate.Disabled = false
							anim:Stop()
							piggy.Humanoid.WalkSpeed = 14
							piggy.Humanoid.JumpPower = 20
							piggy.Torso.Script.Disabled = false
							debounce = false	
						end
						-- Enable debounce so stun effect cannot be applied again for 20 seconds

						piggy:FindFirstChild("Stunned"):Destroy() -- Delete stunned tag so we can tell from other scripts that the
						-- piggy is no longer stunned.
					end
				end
			end		
		end
	end
end)
