Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Enemy knockback script doesn't work when I add wait(1)?

Hi. I'm trying to make the enemy push back the player. But for some reason whenever I add wait(1) it just stops working. How can I fix this? Thanks in advance.

Here's the enemy knockback script:

part = script.Parent
local h 

function onTouch(hit)
	h = hit.Parent:FindFirstChild("Humanoid")
	if h ~= nil then
		hit.Parent.HumanoidRootPart.Velocity = part.CFrame.lookVector * 100
	end
end
part.Touched:connect(onTouch)

With wait(1):

part = script.Parent
local h 

function onTouch(hit)
	h = hit.Parent:FindFirstChild("Humanoid")
	if h ~= nil then	
		wait(1)
		hit.Parent.HumanoidRootPart.Velocity = part.CFrame.lookVector * 100
	end
end
part.Touched:connect(onTouch)

1 answer

✓ Accepted answer

You can use this function to set the velocity:

local RunService = game:GetService("RunService")

function SetVelocity(part, velocity)
	for i=1, 2 do
		RunService.Heartbeat:Wait()
		part.Velocity = velocity
	end
end

--[[ for more details on why this works, see https://devforum.roblox.com/t/how-can-i-put-velocity-on-a-humanoid/337253 ]]

you could also add some kind of debounce since it could knockback the player more than once because of the wait(1).

This discussion is preserved as it was. New answers, comments, and votes are closed.