The random PlayerPicker() function works but the TpToPlayer doesn't tp the monster to the player but to the centre of the map
01 | local Players = game.Players:GetPlayers() |
02 | local nplrs = #Players |
03 | local Randomplayer = nil |
04 | local MonsterTorso = script.Parent.Torso |
05 |
06 |
07 | local function PlayerPicker() |
08 | if nplrs > 0 then |
09 | Randomplayer = Players [ math.random( 1 , nplrs) ] |
10 | end |
11 |
12 | end |
13 |
14 | local function TpToPlayer() |
15 | MonsterTorso.CFrame = CFrame.new(Vector 3. new( 10 , Randomplayer, Randomplayer)) |
16 | 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
01 | local plrServ = game:GetService( 'Players' ) |
02 |
03 | local function PlayerPicker() |
04 | local Players = plrServ:GetPlayers() |
05 |
06 | if #Players > 0 then |
07 | local RandomPlayer = Players [ math.random( 1 , #Players) ] |
08 | if RandomPlayer.Character then -- character will be nil if they have not spawned |
09 | RandomPlayer.Character.Torso.CFrame -- return the player position |
10 | end |
11 | end |
12 | -- you need to handle if there are no players do you return a def CFrame ? |
13 | -- or if the player has no character |
14 | 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)
1 | local function TpToPlayer() |
2 | local teleportTo = PlayerPicker() * CFrame.new( 0 , 0 , - 10 ) -- move back 10 studs |
3 | MonsterTorso.CFrame = teleportTo |
4 | 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:
01 | local Players = game.Players:GetPlayers() |
02 | local nplrs = #Players |
03 | local Randomplayer = Players#nplrs |
04 | local MonsterTorso = script.Parent.Torso |
05 |
06 |
07 | local function PlayerPicker() |
08 | if nplrs > 0 then |
09 | Randomplayer = Players [ math.random( 1 , nplrs) ] |
10 | end |
11 |
12 | end |
13 |
14 | local function TpToPlayer() |
15 | MonsterTorso.CFrame = CFrame.new(Vector 3. new( 10 , Randomplayer, Randomplayer)) |
16 | end |
17 | TpToPlayer() |