The random PlayerPicker() function works but the TpToPlayer doesn't tp the monster to the player but to the centre of the map
local Players = game.Players:GetPlayers() local nplrs = #Players local Randomplayer = nil local MonsterTorso = script.Parent.Torso local function PlayerPicker() if nplrs > 0 then Randomplayer = Players[math.random(1, nplrs)] end end local function TpToPlayer() MonsterTorso.CFrame = CFrame.new(Vector3.new(10, Randomplayer, Randomplayer)) end
The main issue is that Randomplayer
is the Player object whcih is not the Players position. As you are getting a list of player at the start of the script it may also cause issue if a player leaves the game.
To avoid this I would put it all in the PickPlayer function
local plrServ = game:GetService('Players') local function PlayerPicker() local Players = plrServ:GetPlayers() if #Players > 0 then local RandomPlayer = Players[math.random(1, #Players)] if RandomPlayer.Character then -- character will be nil if they have not spawned RandomPlayer.Character.Torso.CFrame-- return the player position end end -- you need to handle if there are no players do you return a def CFrame ? -- or if the player has no character end
Now that you have the players position we can work out what is "back" from the charactes CFrame. We can work in object space (this is outside the scope of this question please reaserch this if you do not know what it is)
local function TpToPlayer() local teleportTo = PlayerPicker() * CFrame.new(0,0, -10) -- move back 10 studs MonsterTorso.CFrame = teleportTo end
You may find that using CFrame will teleport the monster into object in which case you would want to use Position as it will then teleport the monster on top of object.
I hope this helps. Please comment if you have any other questions about this post.
Try this:
local Players = game.Players:GetPlayers() local nplrs = #Players local Randomplayer = Players#nplrs local MonsterTorso = script.Parent.Torso local function PlayerPicker() if nplrs > 0 then Randomplayer = Players[math.random(1, nplrs)] end end local function TpToPlayer() MonsterTorso.CFrame = CFrame.new(Vector3.new(10, Randomplayer, Randomplayer)) end TpToPlayer()