I have a script here that simply moves a dummy to a tree, moves the tree onto the dummy and then the dummy drops it off.
My problem is trying to get the dummy to go to the closest tree, for some reason it is not working.
local dummy = script.Parent
local humanoid = dummy:FindFirstChildOfClass("Humanoid")
local trees = game.Workspace.Trees
local homebase = game.Workspace.HomeBase
local hasTree = false
local function moveToPosition(position)
humanoid:MoveTo(position)
humanoid.MoveToFinished:Wait()
end
local function collectTree(tree)
if not hasTree and tree then
print("Moving to tree")
moveToPosition(tree.Position)
tree.Anchored = false
local vec = Vector3.new(dummy["Right Arm"].Position.X, dummy["Right Arm"].Position.Y + 1, dummy["Right Arm"].Position.Z)
tree.Position = vec
tree.Orientation = Vector3.new(0, 0, 90)
local weld = Instance.new("WeldConstraint")
weld.Name = "TreeWeld"
weld.Part0 = tree
weld.Part1 = dummy:FindFirstChild("Right Arm")
weld.Parent = dummy
print("Tree collected")
hasTree = true
tree.Parent = dummy
end
end
local function returnToHomebase()
if hasTree then
print("Returning home with tree")
humanoid:MoveTo(homebase.Position + Vector3.new(0, 3, 0))
print("Dropping off tree at homebase")
humanoid.MoveToFinished:Wait()
if dummy:FindFirstChild("Tree") then
dummy:FindFirstChild("Tree").Parent = game.Workspace.CollectedTrees
else
warn("Yeilding for Tree Find")
end
local weld = dummy:FindFirstChild("TreeWeld")
if weld then
weld:Destroy()
end
hasTree = false
end
end
while true do
wait(0.25)
local MaxDist = math.huge
local ClosestPart
local DummyHRP = dummy.HumanoidRootPart
for _,v in pairs(trees:GetChildren()) do
if v:IsA("BasePart") then
local Dist = (DummyHRP.Position - v.Position).magnitude
--warn(Dist)
if Dist < MaxDist then
MaxDist = Dist
ClosestPart = v
if not hasTree then
if v then
print(math.round(Dist))
if v.Parent.Name == "Trees" and v.Parent == game.Workspace.Trees then
collectTree(v)
v.Parent = game.Workspace.GettingCollected
else
print("No tree found")
end
end
else
returnToHomebase()
end
end
end
end
end