Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Teleport The Nearest Object? [HELP]

Asked by 6 years ago
Edited 6 years ago

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
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 User#20388 0 — 6y
0
^ lol User#21908 42 — 6y
0
I Need Help. Kallisus 43 — 6y
0
Dude, I answered your question. Just scroll down this page. User#21908 42 — 6y
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. User#21908 42 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago

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!

0
Thanks I didn't saw it But I see It Now xd Kallisus 43 — 6y
0
@Kallisus if he helped, accept his answer Leamir 3138 — 6y
Ad

Answer this question