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

I'm having trouble with a click to teleport script, can anyone help?

Local Script

print(1)
local mse = game.Players.LocalPlayer:GetMouse()
print(2)
mse.Button1Down:connect(function(plr)
	print(3)
	plr.Character.HumanoidRootPart.Position = Vector3.new(mse.Hit.X, mse.Hit.Y, mse.Hit.Z)
	print(4)
end)

2 answers

Button1Down doesn't pass the player. Use the LocalPlayer property of Players, and use UserInputService instead.

local offset = CFrame.new(0, 3, 0)
local client = game:GetService("Players").LocalPlayer
local mouse = client:GetMouse()
local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(input, gpe)
    if gpe then return end -- interacted with gui
    
    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        client.Character:SetPrimaryPartCFrame(CFrame.new(mouse.Hit.Position) * offset)
    end
end) 

I use :SetPrimaryPartCFrame(), as Vector3 factors in collision, and CFrame does not. I just create a CFrame positioned at mouse.Hit.Position and multiply the CFrame by offset so they don't get stuck in the ground


####Don't forget to accept if this helps

local p = game.Players.LocalPlayer
local UIS = game:GetService("UserInputService")
local mouse = p:GetMouse()

function GetCharacter() -- gets the character
	return p.Character
end

function Teleport(position)
	local Char = GetCharacter()
	if Char then
		Char:MoveTo(position) -- moveto mouse.Hit
	end
end


UIS.InputBegan:Connect(function(input,typing)
	if input.UserInputType == Enum.UserInputType.MouseButton1 and not typing and UIS:IsKeyDown(Enum.KeyCode.E) then -- if you're not typing and clicking while holding e
		Teleport(mouse.Hit.p) -- teleport to the position
	end
end)

this 1 is better because you can hold down a key and click to teleport just hold down e

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