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

How to teleport a player in a direction relative to their rotation and position?

Asked by 7 years ago

I get the basic idea of teleportation.

character.HumanoidRootPart.CFrame = CFrame.new(Vector3.new(0, 50, 0))

But what if I wanted to teleport a player x studs left/right/forward, relative to where their character is facing? I'm bad at CFrames.

1 answer

Log in to vote
0
Answered by 7 years ago

A CFrame contains its objects axis shown here.

As these reflect the direction relation to the object we can use these to add onto the current position giving the new position with the given number of studs away.

Example:-

local function teleport(playerChar, direction, amount)
    local charCFrame = playerChar.PrimaryPart.CFrame    

    -- get the vector we want to change
    local dirctionVector
    if direction == 'left' then
        dirctionVector = -charCFrame.rightVector
    elseif direction == 'right' then
        dirctionVector = charCFrame.rightVector
    elseif direction == 'foward' then
        dirctionVector = charCFrame.lookVector
    elseif direction == 'backward' then
        dirctionVector = -charCFrame.lookVector
    elseif direction == 'up' then
        dirctionVector = charCFrame.upVector
    elseif direction == 'down' then
        dirctionVector = -charCFrame.upVector
    else
        return
    end 

    --  multiply the direction with the given amount to get the offset amount to add tho the CFrame
    playerChar.PrimaryPart.CFrame = playerChar.PrimaryPart.CFrame + (dirctionVector * amount)

-- test
wait(5)
teleport(game.Players.Player1.Character, 'left', 20)
end

I hope this helps, please comment if you do not understand how this code works.

Ad

Answer this question