EXTREME Lag from a simple .Touched function

Here you can see my basic rotating pads. They run a script that looks like this:

for _, part in script.Parent:GetChildren() do
	if part.Name == "Pads" then
		local bounce = {}

		part.Touched:connect(function(hit)
			if bounce[hit.Parent] then return end
			bounce[hit.Parent] = true
			task.delay(1, function()
				bounce[hit.Parent] = nil
			end)
			local Character = _G.ModelToCharacter[hit.Parent]
			if not Character then return end

			local velocity = ((Character.HRP.Position - hit.Position).Unit + Vector3.new(0, 1, 0)).Unit * 65
			Character:BounceDamage(10, part , velocity)
		end)
	end
end

BounceDamage inside the Character looks like this

function Character:BounceDamage(damage, Killer, velocity)
	if self.Bounce[Killer] then return false end
	
	self.Bounce[Killer] = true
	
	task.delay(.5, function()
		self.Bounce[Killer] = nil
	end)
	print("Take damage")
	return self:TakeDamage(damage, nil, velocity)
end

function Character:TakeDamage(damage, Killer, velocity)
	if self.isForceField or self.isLobbyCharacter then return false end
	
	if self.isBlocking and velocity then 
		if velocity:Dot(self.HRP.CFrame.lookVector) < 0 then 
			self.onBlocked:Fire()
			return false 
		end --Blocked
	end
	
	local humanoid = self.Humanoid
	
	self:PlaySound("Hit")
	
	if humanoid:GetAttribute("isDead") then 
		self:SetVelocity(velocity, .2)
		
		return false 
	end

	local prevHealth = humanoid:GetAttribute("Health")
	local isKilled = damage >= prevHealth
	if isKilled then
		damage = prevHealth
	end
	local health = prevHealth - damage
	humanoid:SetAttribute("Health", health)
	
	
	_G.FX("Hit", self.HRP)
	
	self:SetRagdoll(true)
	self:SetVelocity(velocity, .2)
	
	if velocity and velocity.magnitude > 50 then
		self:SetParticle("Smoke", true, 0.8)
	end
	
	if isKilled then
		humanoid:SetAttribute("isDead", true)
		
		self.onDeath:Fire(Killer)
		return true
	end

	if Killer and Killer.Player then
		_G.DropCoins(Killer.Player, self.HRP.Position, 10)
		Killer:GiveWeaponExperience(10)
	end
	
	
	task.delay(2, function()
		self:SetRagdoll(false)
	end)
end

And “Take damage” is just printed once. Even so, you can see how the entire screen freeze up.
Anyone have any qualified guesses as to why?

I use _G.ModelToCharacter in many scripts to get character (like when you tell server to attack) but nothing is using it as of this moment.

Your microprofiler shows that the frametime is fine, which is odd.

On first inspection, try looking at lines that can cause hanging, mainly the debounces and task.delay() lines.

1 Like

Turns out it was setVelocity that set NaN velocity locally.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.