The nearest enemy detection is not working

What do you want to achieve? So, i’m trying to make my hitbox to only hit one enemy at time, which is not rappening properly, sometimes the function return the nearest enemy (which i want to rappen all the time), sometimes the farthest, and sometimes the 2 enemies that i hit with my hitbox (i’m describing what is rappening when i hit 2 enemies)

here is my script:

local RP = game:GetService("ReplicatedStorage")
local grabRemote = RP.remotes.grab
local ss = game:GetService("ServerStorage")
local modules = ss:WaitForChild("Modules")
local slow = require(modules:WaitForChild("slow"))
local runService = game:GetService("RunService")
local rockModule = require(modules:WaitForChild("RockModule"))
local utilities = require(modules:WaitForChild("particleEmitter"))
local hitbox = require(modules:WaitForChild("hitbox"))
local hitService = require(modules:WaitForChild("hitService"))

local hitedPeople = {}
local grabAnins = {}

local looping = false

local startTick
local weld
local enemy
local enemyHumRP
local closestDist = math.huge
local target = nil
local targetRP = nil

local function getTarget(Enemy,hrp,tableE)
	closestDist = math.huge
	table.insert(tableE,Enemy)
	
	if #hitedPeople > 0 then
		for i,enemyChar in pairs(hitedPeople) do
			local enemyRP = enemyChar.HumanoidRootPart
			local distance = (enemyChar.HumanoidRootPart.Position - hrp.Position).Magnitude
			
			if distance < closestDist then
				closestDist = distance
				target = enemyChar
				targetRP = target.HumanoidRootPart
			end
		end
	end
end

local function aplyVelocity(targetHumRP,direction)
	local linearV = Instance.new("LinearVelocity",targetHumRP)
	local attach = targetHumRP.RootAttachment
	linearV.MaxForce = 100000
	linearV.ForceLimitMode = Enum.ForceLimitMode.PerAxis
	linearV.MaxAxesForce = Vector3.new(100000,0,100000)
	linearV.VectorVelocity = direction
	linearV.VelocityConstraintMode = Enum.VelocityConstraintMode.Vector
	linearV.Attachment0 = attach
	linearV.RelativeTo = Enum.ActuatorRelativeTo.Attachment0
	attach.WorldPosition = targetHumRP.AssemblyCenterOfMass
	linearV.ForceLimitsEnabled = true
	game.Debris:AddItem(linearV,0.2)
end

grabRemote.OnServerEvent:Connect(function(plr,grab,input)	
	local character = plr.Character
	local humanoid = character:WaitForChild("Humanoid")
	local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")

	local grabing = character:GetAttribute("Grab")
	local attacking = character:GetAttribute("Attacking")
	local punching = character:GetAttribute("Punching")
	local blocking = character:GetAttribute("Blocking")
	local jumping = character:GetAttribute("Jumping")
	local slowed = character:GetAttribute("Slowed")
	local stunned = character:GetAttribute("Stunned")
	local dashing = character:GetAttribute("Dash")
	local dashing2 = character:GetAttribute("Dash2")

	if grab then
		if grabing or attacking or punching or blocking or stunned or dashing or dashing2 then return end

		local animation = Instance.new("Animation")
		animation.AnimationId = "http://www.roblox.com/asset/?id=anim"
		local animationTrack = humanoid:LoadAnimation(animation)

		local animationGrabing = Instance.new("Animation")
		animationGrabing.AnimationId = "http://www.roblox.com/asset/?id=anim"
		local animationTrackGrabing = humanoid:LoadAnimation(animationGrabing)

		local hitbox = hitbox.new()
		hitbox.Size = Vector3.new(14,14,14)
		hitbox.CFrame = humanoidRootPart
		hitbox.Offset = CFrame.new(0,0,-2)
		hitbox.Visualizer = true

		hitbox.onTouch = function(enemyHum)
			if enemyHum ~= humanoid then				
				looping = true
				character:SetAttribute("Grab",true)
				enemy = enemyHum.Parent
				enemyHumRP = enemy.HumanoidRootPart
				
				
				getTarget(enemy,humanoidRootPart,hitedPeople)

				print(hitedPeople)
				print(target)

				for i,v in pairs(target:GetChildren()) do
					if v:IsA("BasePart") then
						v.Color = Color3.fromRGB(0,100,80)
					end
				end

				weld = Instance.new("Weld")
				weld.C1 = CFrame.new(0,0,-2) * CFrame.Angles(0,math.rad(180),0)
				weld.Part0 = targetRP
				weld.Part1 = humanoidRootPart
				weld.Name = "wellwellwell"

				local knockback = nil
				local maxForce = nil

				startTick = tick()

				while looping do
					humanoid.WalkSpeed = 10
					humanoid.JumpPower = 0

					weld.Parent = targetRP
					target.Humanoid.PlatformStand = true


					if tick() - startTick > 3 then			
						print(target,targetRP)
						character:SetAttribute("Grab",false)
						target.Humanoid.PlatformStand = false
						humanoid.WalkSpeed = 20
						humanoid.JumpPower = 50

						for i,v in pairs(targetRP:GetChildren()) do
							if v:IsA("Weld") and v.Name == "wellwellwell" then
								v.Parent = nil
							end
						end


						aplyVelocity(targetRP,Vector3.new(0,0,30))

						hitedPeople = {}

						break
					end

					task.wait()
				end

				hitService.hit(enemyHum,nil,knockback,nil,character,nil,nil,maxForce,nil,nil)

			end	
		end

		animationTrack.KeyframeReached:Connect(function(kf)
			if kf == "grab" then
				hitbox:Start()
				task.wait(0.2)
				hitbox:Stop()
			end
		end)

		animationTrack:Play()
		grabAnins[plr] = animationTrack
	else
		if grabing then				
			looping = false
			character:SetAttribute("Grab",false)
			grabAnins[plr]:Stop()
			grabAnins[plr] = nil

			humanoid.WalkSpeed = 20
			humanoid.JumpPower = 50

			target.Humanoid.PlatformStand = false

			for i,v in pairs(targetRP:GetChildren()) do
				if v:IsA("Weld") and v.Name == "wellwellwell" then
					v.Enabled = false
				end
			end

			if tick() - startTick < 3 and input == Enum.KeyCode.T then
				aplyVelocity(targetRP,Vector3.new(0,0,30))
			elseif input == Enum.KeyCode.Y then
				aplyVelocity(targetRP,Vector3.new(30,0,0))
			elseif input == Enum.KeyCode.G then
				aplyVelocity(targetRP,Vector3.new(-30,0,0))
			end			

			hitedPeople = {}
		end

	end	
end)

What is the issue?

here is a video that show what is happening:

and here is a print of the hitedPeople table:

– you can notice that print the table just with the target, and them it print a secondy time with the target always in first and the enemy who is not the target (i don’t know why it’s rappening)

whats the table count after the first hit??

oh, ok. my english is not so good

1 Like

wait, its printing nil dsrthdgertyherg

can u show a photo please of the prints

of course sdefgsetrhgwsregstrh

here:

(wtf, my shirt colour changed :rofl: :rofl: :rofl:)

it prints nil even when the target bugs

its probably finding the same target root part to weld to, change it to if its a new target then add it

how would i do that? in the getTarget function you mean?

Hey, can you show me where you add an enemy to the hitedpeople array?

I’ve looked through the script and i couldn’t find any table.insert(hitedpeople, enemy) or hitedpeople = {Enemy} anywhere.

in the begin of the getTarget function

i already mentioned this in ur post on the other subject with the same issue, that hitbox.onTouch is more of a touch event, not a workspace:GetPartsBoundInBox , therefore it doesnt take the nearest enemy, it takes the first enemy it can read

i have just put the print in the wrong place, its printing the target

have a bit of stress-tolerance and try this script again and let us know about the error outputs

local grabRemote = RP.remotes.grab
local ss = game:GetService("ServerStorage")
local modules = ss:WaitForChild("Modules")
local slow = require(modules:WaitForChild("slow"))
local runService = game:GetService("RunService")
local rockModule = require(modules:WaitForChild("RockModule"))
local utilities = require(modules:WaitForChild("particleEmitter"))
local hitbox = require(modules:WaitForChild("hitbox"))
local hitService = require(modules:WaitForChild("hitService"))

local hitedPeople = {}
local grabAnins = {}

local looping = false

local startTick
local weld
local enemy
local enemyHumRP

local TheTarget = nil
local TheTargetRP = nil



local function aplyVelocity(targetHumRP,direction)
	local linearV = Instance.new("LinearVelocity",targetHumRP)
	local attach = targetHumRP.RootAttachment
	linearV.MaxForce = 100000
	linearV.ForceLimitMode = Enum.ForceLimitMode.PerAxis
	linearV.MaxAxesForce = Vector3.new(100000,0,100000)
	linearV.VectorVelocity = direction
	linearV.VelocityConstraintMode = Enum.VelocityConstraintMode.Vector
	linearV.Attachment0 = attach
	linearV.RelativeTo = Enum.ActuatorRelativeTo.Attachment0
	attach.WorldPosition = targetHumRP.AssemblyCenterOfMass
	linearV.ForceLimitsEnabled = true
	game.Debris:AddItem(linearV,0.2)
end

local function GetAllEnemiesWithinHitbox(Hitbox, MyHumanoid)
	local AllEnemies = {}
	local CurrentDistance = math.huge
	local CurrentTarget = nil
	local CurrentTargetHRP = nil
	
	local Array = workspace:GetPartBoundsInBox(hitbox.CFrame, hitbox.Size)
	
	if Array ~= nil then
		for i, v in Array do
			local Model = v:FindFirstAncestorOfClass("Model")
			if Model then
				local Hum = Model:FindFirstChild("Humanoid")
				if Hum and Hum ~= MyHumanoid then
					
					local Dist = (Model.PrimaryPart.Position - MyHumanoid.Parent.PrimaryPart.Position).Magnitude
					
					if Dist < CurrentDistance then
						CurrentTarget = Model
						CurrentDistance = Dist
						CurrentTargetHRP = Model:FindFirstChild("HumanoidRootPart")
					end
					
				end
			end
		end
	end
	
	return CurrentTarget, CurrentTargetHRP
	
end

grabRemote.OnServerEvent:Connect(function(plr,grab,input)	
	local character = plr.Character
	local humanoid = character:WaitForChild("Humanoid")
	local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")

	local grabing = character:GetAttribute("Grab")
	local attacking = character:GetAttribute("Attacking")
	local punching = character:GetAttribute("Punching")
	local blocking = character:GetAttribute("Blocking")
	local jumping = character:GetAttribute("Jumping")
	local slowed = character:GetAttribute("Slowed")
	local stunned = character:GetAttribute("Stunned")
	local dashing = character:GetAttribute("Dash")
	local dashing2 = character:GetAttribute("Dash2")

	if grab then
		if grabing or attacking or punching or blocking or stunned or dashing or dashing2 then return end

		local animation = Instance.new("Animation")
		animation.AnimationId = "http://www.roblox.com/asset/?id=85032147152709"
		local animationTrack = humanoid:LoadAnimation(animation)

		local animationGrabing = Instance.new("Animation")
		animationGrabing.AnimationId = "http://www.roblox.com/asset/?id=anim"
		local animationTrackGrabing = humanoid:LoadAnimation(animationGrabing)

		local function GrabFunc()
			local hitbox = Instance.new("Part")
			hitbox.Name = "HitBox"
			hitbox.Transparency = 1
			hitbox.CanCollide = false
			hitbox.Anchored = true
			hitbox.Size = Vector3.new(14,14,14)
			hitbox.CFrame = humanoidRootPart.CFrame + Vector3.new(0, 0, -2)

			local Target, TargetHRP = GetAllEnemiesWithinHitbox(hitbox)

			if Target ~= nil then
				
				TheTarget = Target
				TheTargetRP = TargetHRP
				
				looping = true
				character:SetAttribute("Grab",true)
				enemy = Target
				enemyHumRP = TargetHRP

				for i,v in pairs(Target:GetChildren()) do
					if v:IsA("BasePart") then
						v.Color = Color3.fromRGB(0,100,80)
					end
				end

				weld = Instance.new("Weld")
				weld.C1 = CFrame.new(0,0,-2) * CFrame.Angles(0,math.rad(180),0)
				weld.Part0 = TargetHRP
				weld.Part1 = humanoidRootPart
				weld.Name = "wellwellwell"

				local knockback = nil
				local maxForce = nil

				startTick = tick()

				while looping do
					humanoid.WalkSpeed = 10
					humanoid.JumpPower = 0

					weld.Parent = TargetHRP
					Target.Humanoid.PlatformStand = true


					if tick() - startTick > 3 then			
						print(Target,TargetHRP)
						character:SetAttribute("Grab",false)
						Target.Humanoid.PlatformStand = false
						humanoid.WalkSpeed = 20
						humanoid.JumpPower = 50

						for i,v in pairs(TargetHRP:GetChildren()) do
							if v:IsA("Weld") and v.Name == "wellwellwell" then
								v.Parent = nil
							end
						end


						aplyVelocity(TargetHRP,Vector3.new(0,0,30))

						break
					end

					task.wait()
				end

				hitService.hit(Target.Humanoid,nil,knockback,nil,character,nil,nil,maxForce,nil,nil)

			end	
		end
		


		animationTrack.KeyframeReached:Connect(function(kf)
			if kf == "grab" then
				GrabFunc()
			end
		end)

		animationTrack:Play()
		grabAnins[plr] = animationTrack
	else
		if grabing then				
			looping = false
			character:SetAttribute("Grab",false)
			grabAnins[plr]:Stop()
			grabAnins[plr] = nil

			humanoid.WalkSpeed = 20
			humanoid.JumpPower = 50

			TheTarget.Humanoid.PlatformStand = false

			for i,v in pairs(TheTargetRP:GetChildren()) do
				if v:IsA("Weld") and v.Name == "wellwellwell" then
					v.Enabled = false
				end
			end

			if tick() - startTick < 3 and input == Enum.KeyCode.T then
				aplyVelocity(TheTargetRP,Vector3.new(0,0,30))
			elseif input == Enum.KeyCode.Y then
				aplyVelocity(TheTargetRP,Vector3.new(30,0,0))
			elseif input == Enum.KeyCode.G then
				aplyVelocity(TheTargetRP,Vector3.new(-30,0,0))
			end			

			hitedPeople = {}
		end

	end	
end)

could tou explaim me how getPartsBoundInBox works?

it gets the data of the hitbox (the part) and Go through every part that is within that box and put it into array and i made a loop that goes through all of those array and finds the nearest enemy

hitbox.onTouch on the other hand is an event that waits who touch the hitbox, therefore its matter of who touch first, rather than whos nearest

how could i explaim it, my hitbox is not a part

In line 25, you set the hitedpeople variable to ‘tableE’ so you need to change the hitedpeople in if #hitedPeople > 0 then and the for i,enemyChar in pairs(hitedPeople) do to tableE instead

thats why i made the script for u, i converted ur hitbox into a part with cframe and size