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

Teleport script on keypress not working. Is my code formatted correctly?

Asked by 6 years ago

I am trying to teleport a user when key 'V' is pressed on the keyboard. I figured this would be an easy task but I must be missing something here...

local PlayerName = game.Players.LocalPlayer.Name
if game:getService("UserInputService"):IsKeyDown(Enum.KeyCode.V) then
game.Workspace[PlayerName]:MoveTo(Vector3.new(234,4.31,446.92))
end
end

If anyone could tell me what I am doing wrong it would be more than appreciated!

1 answer

Log in to vote
0
Answered by 6 years ago

You're close.

The IsKeyDown method of UserInputService will return true if you are pressing the key with the key code you pass. The check is only made once, the script won't check again. Using the InputBegan event you can do the check there.

local client = game:GetService("Players").LocalPlayer
-- better way of getting a service. workspace you don't really need to use this.

game:GetService("UserInputService").InputBegan:Connect(function(input, gpe)
    if gpe then return end -- if in a textbox, stop the function

    if input.KeyCode == Enum.KeyCode.V then
        client.Character:SetPrimaryPartCFrame(CFrame.new(234,4.31,446.92))
        -- Using cframe to teleport to prevent conflict with possible parts
    end
end)

Finally, indexing the character from the workspace is not a good idea. If a user named Terrain or Part joined your game your script would break, lol


Hopefully this answered your question, and if it did, then don't forget to hit that accept button. If you have any other questions then feel free to leave them down in the comments.
1
Ok this is good information to know, I really appreciate this. I was doing it the choppy way, never even thought about the username thing. Thanks!! PieBoots 16 — 6y
Ad

Answer this question