Region3 hitbox not damaging player?

I’m trying to make a combat system right now and I made a module for it that creates the hitbox. It sort of worked the first test except it immediately killed the player that was attacked. Then I tired to add a debounce using a table and now it won’t damage the player at all.

ModuleScript:

local Hitbox = {}

local PlayersHit = {}

function Hitbox.CreateHitbox(character, position)
	local Part = Instance.new("Part", character)
	Part.Anchored = true
	Part.CanCollide = false
	Part.Transparency = 1
	Part.Size = Vector3.new(4,4,4)
	Part.Position = position
	return Part
end

function Hitbox.GetMin(part)
	local min = Vector3.new(part.Position.X - part.Size.X/2, part.Position.Y - part.Size.Y/2, part.Position.Z - part.Size.Z/2)
	return min
end

function Hitbox.GetMax(part)
	local max = Vector3.new(part.Position.X + part.Size.X/2, part.Position.Y + part.Size.Y/2, part.Position.Z + part.Size.Z/2)
	return max
end

function Hitbox.RunHitbox(part, region, character, damage)
	
	local PartsInRegion = workspace:FindPartsInRegion3(region, part, 10)
	for index, PartInRegion in pairs(PartsInRegion) do
		if PartInRegion.Parent:FindFirstChildOfClass("Humanoid") then
			for index, PlayerHit in pairs(PlayersHit) do
				if PartInRegion.Parent == PlayerHit then
					return
				else
					table.insert(PlayersHit, PartInRegion.Parent)
					PartInRegion.Parent:FindFirstChildOfClass("Humanoid"):TakeDamage(damage)
				end
			end
		end
	end
	
	table.clear(PlayersHit)
end

function Hitbox.CreateStateValue(name, character)
	local Value = Instance.new("BoolValue", character)
	Value.Value = true
	Value.Name = name
	return Value
end

return Hitbox

1 Like

You’re trying to loop through an empty table when you hit a part with a humanoid, which results in the code not running at all. Instead of doing that, you can create an index in the table with the player’s name, and check if that index exists before dealing damage.
Example:

for index, PartInRegion in pairs(PartsInRegion) do
	if PartInRegion.Parent:FindFirstChildOfClass("Humanoid") ~= nil then
		if PlayersHit[PartInRegion.Parent] then
			continue
		else
			print("Success")
			PlayersHit[PartInRegion.Parent] = true
			PartInRegion.Parent.Humanoid:TakeDamage(damage)
		end
	end
end

Also, I don’t recommend using Region3’s. There are different API’s that supercede it like Blockcasts, Spherecasts, and OverlapParams.
It would help to learn about Object-Oriented Programming in Lua too, since it’ll allow you to remove the part parameter in the module’s functions in favor of using self.

1 Like

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