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

How To get Player character to move to a position when onTouched?

Asked by 7 years ago

What I am trying to do is to get the player to move to a position when it touches a part. This is the script I used

workspace.Custom.Touched:connect(function(hit) local pos = game.Workspace.Spot.Position game.Players.LocalPlayer:MoveTo(pos)

end)

It says MoveTo isn't a valid member of Player, what do I replace it with?

2 answers

Log in to vote
0
Answered by
Asceylos 562 Moderation Voter
7 years ago

What you need to do is get the character of the player:

workspace.Custom.Touched:connect(function(hit) local pos = game.Workspace.Spot.Position game.Players.LocalPlayer.Character:MoveTo(pos)
end)
0
That wouldn't work because of LocalPlayer. TheDeadlyPanther 2460 — 7y
0
Why would it not work? What do you mean? I added .Character to the LocalPlayer which gets its character. Asceylos 562 — 7y
0
Because LocalPlayer can't be accessed from a normal script and you shouldn't use a LocalScript with this type of script, else anyone that touches the brick is going to cause the client to teleport. Azarth 3141 — 7y
0
Apparently he did use a LocalScript. Asceylos 562 — 7y
Ad
Log in to vote
0
Answered by
Azarth 3141 Moderation Voter Community Moderator
7 years ago

LocalPlayer can't be accessed in a normal script, but you can use the GetPlayerFromCharacter method to obtain who hit the brick. Start good practices now, like DRY (Don't repeat anything) and index variables before you need them.

local custom = workspace:WaitForChild("Custom")
-- You only need to index Spot's position once, unless it moves. 
local pos = workspace:WaitForChild("Spot").Position
-- connect is deprecated, use Connect.
custom.Touched:Connect(function(hit) 
    -- Check to see if hit.Parent is a valid member of players
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player and player.Character then 
        local hum = player.Character:findFirstChild("Humanoid")
        -- Make sure we aren't dead
        if hum and hum.Health > 0 then 
            player.Character:MoveTo(pos)
        end
    end
end)

Answer this question