this script is meant to make its parent part move towards the player, but when it's running the part just falls down into the void. I can't just anchor the part, as then it can't move towards the player.
local part = script.Parent
local speed = 1
local function findNearestPlayer()
local players = game.Players:GetPlayers()
local nearestPlayer = nil
local nearestDistance = math.huge
for _, player in ipairs(players) do
local character = player.Character
if character then
local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
if humanoidRootPart then
local distance = (humanoidRootPart.Position - part.Position).magnitude
if distance < nearestDistance then
nearestPlayer = player
nearestDistance = distance
end
end
end
end
return nearestPlayer
end
while true do
local nearestPlayer = findNearestPlayer()
if nearestPlayer then
local character = nearestPlayer.Character
if character then
local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
if humanoidRootPart then
local targetPosition = humanoidRootPart.Position
local currentPosition = part.Position
local direction = (targetPosition - currentPosition).unit
local newPosition = currentPosition + direction * speed * workspace.DeltaTime
part.Position = newPosition
end
end
end
wait()
end