Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Teleport The Nearest Object? [HELP]

Can Someone Fix This Script For Me I Need It Where It Teleport's To Me The Nearest Object

for i,v in pairs(game.Workspace:GetDescendats()) do 
if v.Name == "Object" then 
v.CFrame = game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame * CFrame.new(0,0,-3.7)
end
end

5 comments

0

When they say "include a script to show you've attempted to solve your problem", they don't actually mean to add a random script that has nothing to do with it, also, it's not that hard to find

0

^ lol

0

I Need Help.

0

Dude, I answered your question. Just scroll down this page.

0

If I helped you out please accept my answer. It is considered a courtesy if someone helps you out. If you don't end up accepting my answer, at least accept the answers that other people give you in the future.

1 answer

✓ Accepted answer

You need to have a variable with the closest object's position in it and if you find a closer object putting it into that variable. Then, when the loop is done, teleport the player to the object in the variable. You can use Magnitude to find the distance. Here is an example:

local players = game:GetService("Players") -- this is the recommended method for getting the service players
local player = players.LocalPlayer
local closestDistanceFound -- will define this in the loop
local teleportPosition -- same as ^
local character = player.CharacterAdded:Wait() -- gonna wait for the character
local humanoidRootPart = character.HumanoidRootPart -- this is the part of the player we will be using to teleport
wait(5) -- wait for everything to load in for this example
for i,v in pairs(game.Workspace:GetDescendants()) do
	if v.Name == "Object" then -- if you just want to see if it is a basepart you could do if v:IsA("BasePart") then
		local distanceFromPlayer = (v.Position - humanoidRootPart.Position).Magnitude
		if not closestDistanceFound then
			if closestDistanceFound > distanceFromPlayer then
				closestDistanceFound = distanceFromPlayer
				teleportPosition = v.Position
			end
		else
			closestDistancFound = distanceFromPlayer
			teleportPosition = v.Position
		end
	end
end	
humanoidRootPart.CFrame = CFrame.new(teleportPosition)

I hope this helps and have a great day scripting!

2 comments

0

Thanks I didn't saw it But I see It Now xd

0

@Kallisus if he helped, accept his answer

This discussion is preserved as it was. New answers, comments, and votes are closed.