Search code examples
luaroblox

Roblox: how to place a player in a specific position


I'm a newbie developer of roblox.

I'm trying to place a player in a specific position on first load in this way:

In StarterPlayer > StarterPlayerScripts I added a LocalScript with the following code:

local cf = CFrame.new(500, 5, 50)
local Char = game.Players.LocalPlayer
Char.HumanoidRootPart.CFrame = cf

When I click play, nothing happen onload. What I'm doing wrong?


Solution

  • @ItsJustFunboy is half correct, you do need to use the Model:MoveTo function, but you might have some other issues as well : timing and LocalScripts.

    Timing-wise, you have this code in StarterPlayerScripts. These LocalScripts execute when the Player joins the game, not when their character model appears. So it's possible that their character doesn't even exist at the time you're telling it to move. If you want to guarantee that the character model exists at the time you run this code, it needs to be in StarterCharacterScripts.

    As for the problem with LocalScripts, they make changes to the world only on your client. Meaning that if you move your character in a LocalScript, then all the other players will still see your character model where it was, not where you moved it. So unless this is intentional, if you want everyone to see this change, you need to move the character model in a server-side Script.

    So in a Script in the Workspace or in ServerScriptService, try this :

    -- wait for a player to join the game
    game.Players.PlayerAdded:Connect(function(player)
        -- wait for their character to load into the game
        player.CharacterAdded:Connect(function(character)
            -- yield the thread for but a moment so that the character can finish loading
            wait()
    
            -- move their character
            local targetPosition = Vector3.new(500, 5, 50)
            character:MoveTo(targetPosition)
        end)
    end)