How can I improve my hitbox?

I’m not sure if my code is efficient as possible. I want to keep it as optimized as i can.

Here is the code:

sub(function() is just coroutine wrap

local function startHitbox(duration)
    sub(function()
        local pastTime = tick()
        local connection 
        
        local attachmentTable = {}
        for i,v in pairs(sword:GetChildren()) do
            if v.Name == "DmgPoint" then
                local lastWorldPos = v.WorldPosition
                attachmentTable[v] = {lastPos = lastWorldPos}
            end
        end
        
        connection = RunService.RenderStepped:Connect(function()
            if (tick() - pastTime) >= duration then
                connection:Disconnect()
            end
            
            for i,v in pairs(attachmentTable) do
                local ray = Ray.new(i.WorldPosition, v.lastPos)
                local hit, pos = workspace:FindPartOnRay(ray, char)
                if hit then
                    --hit stuff
                end
                v.lastPos = i.WorldPosition
            end
        end)
    end)
end

A few things I noticed here.

Firstly, the second parameter of Ray.new() looks at the Vector as a Direction, not as an end-point. The Direction and Magnitude represented by the initial position would be undesirable.
I believe what you’d really want is:

Ray.new(i.WorldPosition, (v.lastPos - i.WorldPosition))

Secondly, creating a coroutine from this doesn’t make any sense. The function would never yield.

Thirdly, I’m guessing that attachmentTable is probably going to be the same with each call. If that’s the case you should probably predefine it.

local startHitbox = nil
do
	local attachmentTable = {}
	for i,v in pairs(sword:GetChildren()) do
		-- ...
	end
	startHitbox = function(duration)
		-- ...
	end
end

Finally, this is a nitpick, but tick() is going to return a pretty unnecessarily large number for your usecase. Consider using a smaller alternative such as time() instead.

Thanks for your help. I will fix the things that you told me. Learned a few stuff here :slight_smile: