Hi all, I’m having some trouble with a concept i’m trying to make. Essentially, I am making a system where an NPC finds the nearest enemy part or nearest enemy NPC. The NPC has an attached hitbox to it (using region3) which I want it to allow it to determine whether the enemy is within range of the NPC, by checking if it is inside the region3, so it can perform actions like stopping the NPC and attacking the enemy.
My problem mostly resides inside of a while loop I coded, which will repeatedly call the function to find the nearest enemy part and move to it. It also is meant to constantly check what items are inside of the region3 so it can perform the actions I stated before. It seems to be finding the nearest enemy well, but it is “skipping” the checking of what parts are inside of the hitbox attached to the NPC.
After hours of testing and trying to search up articles, I felt like there was not a sufficient amount of information to fix my problem. Here’s my code:
local noobCharacter = script.Parent
local humanoid = noobCharacter.Humanoid
local rootPart = noobCharacter.HumanoidRootPart
local targetPart = nil
local smallestDistance = math.huge
local regionArea = script.Parent:FindFirstChild("Hitbox")
local positionA = regionArea.Position - (regionArea.Size / 2)
local positionB = regionArea.Position + (regionArea.Size / 2)
local hitbox = Region3.new(positionA,positionB)
local function getTarget()
for i, v in pairs(workspace:GetDescendants()) do
if v:IsA("ObjectValue") and v.Name == "Enemy" then
if v.Parent:IsA("Model") then
local distanceFromNpc = (v.Parent.PrimaryPart.Position - rootPart.position).magnitude
if distanceFromNpc < smallestDistance then
--print(v.Parent.Name .." ".. tostring(distanceFromNpc))
smallestDistance = distanceFromNpc
targetPart = v.Parent.PrimaryPart
end
else
local distanceFromNpc = (v.Parent.Position - rootPart.position).magnitude
if distanceFromNpc < smallestDistance then
--print(v.Parent.Name.." " .. tostring(distanceFromNpc))
smallestDistance = distanceFromNpc
targetPart = v.Parent
end
end
end
end
end
local targetIsInRegion = true
while true do wait(1)
local partsInRegion = workspace:FindPartsInRegion3(hitbox, nil, math.huge)
getTarget()
for i, v in pairs(partsInRegion) do
if targetPart ~= nil then
if v == targetPart then
targetIsInRegion = true
break
else
print("tp is not in region")
targetIsInRegion = false
break
end
end
--print(v.Name)
end
print(targetIsInRegion)
if targetPart ~= nil then
humanoid:MoveTo(targetPart.Position)
getTarget()
targetPart = nil
smallestDistance = math.huge
else
wait()
getTarget()
targetPart = nil
smallestDistance = math.huge
end
print("loop done")
end
Main thing to look at is simply the while loop. If anyone can figure out what is going on and can provide a simple solution, or any alternative methods to writing the code above, it would be greatly appreciated. Thanks