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

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

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

✓ Accepted answer

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)

4 comments

0

That wouldn't work because of LocalPlayer.

0

Why would it not work? What do you mean? I added .Character to the LocalPlayer which gets its character.

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.

0

Apparently he did use a LocalScript.

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)

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