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

How to teleport a monster to a player 10 studs behind?

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

2 comments

0

10 studs in what direction? infront behind

0

Behind

2 answers

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.

1 comment

0

Line 2 on the TpToPlayer() function doesn't work and i receive this error: bad argument #1 to '?' (CFrame expected, got nil)

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()

1 comment

0

the code you just returned is the same as what i posted

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