How would i make this loop faster?

I have a bomb in my game, and i made a custom explosion for it. heres part of my code:

local function push (plr,direction)
	local KnockBack = Instance.new("BodyVelocity")
	KnockBack.Parent = plr 

	KnockBack.MaxForce = Vector3.new(5000,5000,5000)
	KnockBack.Velocity = direction * 200

	wait(0.2)
	KnockBack:Destroy()
end
local hit = workspace:GetPartsInPart(range)
	for i, v in pairs(hit) do
			if v.Parent.Name == "OBJS" then
				local direction = (v.Position - range.Position).unit

				push(v,direction)
			
			
			end
		end

this works well until there are mutiple objects, there is a huge visible delay. i learned that its not possible to have two functions running at the same time, but is there someway i can make it faster?

it is possible to make two functions run at the same time, look up coroutines

1 Like

Following what SteveoAttano said, maybe try:

coroutine.wrap(function() --[[your for i, v loop]] end)

1 Like

Lol sorry I forgot to actually give him an example, I was posting my own problem on the forum and just stopped by this post for fun lol

1 Like

Replace your push() function with this :

local function push (plr,direction)
        spawn(function()
	      local KnockBack = Instance.new("BodyVelocity")
	     KnockBack.Parent = plr 

	     KnockBack.MaxForce = Vector3.new(5000,5000,5000)
	     KnockBack.Velocity = direction * 200

	     wait(0.2)
	     KnockBack:Destroy()
        end)
end

the spawn function creates a new thread without the use of corountine and runs it independently of other threads. this basically allows you to “skip” the wait inside of the function

Not every part needs to be considered for pushing. You can get rid of the unneeded parts, just tag all the appropriate parts with ‘phys’


for i,v in ipairs(game:GetService("CollectionService"):GetTagged("phys")) do
	if (v.Position-range.Position).Magnitude < 10 do
		push()
	end
end

What @3F1VE said, but you can use task.delay or game.Debris too.