So, I'm trying to create a script where a part finds the nearest piece of food and goes to it. Obviously parts themselves can't pathfind so I decided to make an NPC invisible and just weld the part to the NPC's HumanoidRootPart. I ran the game and saw the part nowhere to be seen. I saw a shadow and looked up and then realized the NPC was floating in the air (I could tell it was the whole NPC because I looked in the explorer and the entire NPC was highlighted in the air). I have no idea why is this happening. Here's the script:

local mainpart = script.Parent.HumanoidRootPart
local mainhum = script.Parent.Humanoid

local function findTarget()
	print("find target function fired")
	local finddistance = 50
	local target = nil
	for i, v in pairs(game.Workspace.Food:GetChildren()) do
		print("1")
		if (mainpart.Position - v.Position).magnitude < finddistance then
			print("2")
			finddistance = (mainpart.Position - v.Position).magnitude
			target = v
		end
	end
	return target
end

while wait(1) do
	print("finding target")
	local v = findTarget()
	
	if v then
		print("target found")
		local PathfindingService = game:GetService("PathfindingService")
		local path = PathfindingService:CreatePath()
		
		path:ComputeAsync(mainhum.Parent.Position, v.Visible.Position)
		
		local waypoints = path:GetWaypoints()
		
		for i,vv in pairs(waypoints) do
			mainhum:MoveTo(vv.Position)
		end
	end
	mainhum.MoveToFinished:Wait(5)
end

As you can see, I added prints. It printed "finding target", "find target function fired", and "1(x117)". Since 2 did not print I suspect that this line is the culprit:

if (mainpart.Position - v.Position).magnitude < finddistance then

Still, I have no idea why this behavior is happening. Any help would be appreciated. Thanks!

1 comment

0

it was floating in the air, but did it still move to where it was supposed to?