Camera does not teleport

I want to make it so that when I press the right mouse button it teleports my camera to a part called “cam”
I have this script but it does not work:

-- Variables
local player = game.Players.LocalPlayer
local tool = script.Parent
local userInputService = game:GetService("UserInputService")

-- Function to teleport the camera to the Cam part's position
local function teleportCamera()
	local camera = game.Workspace.CurrentCamera
	local camPart = tool:FindFirstChild("cam") -- Move this line inside the function

	if camPart then
		camera.CFrame = CFrame.new(camPart.Position)
	end
end

-- Function to handle mouse button events
local function onMouseButtonPressed(input)
	if input.UserInputType == Enum.UserInputType.MouseButton2 then -- Right mouse button
		teleportCamera()
	end
end

-- Connect the function to the mouse button pressed event
userInputService.MouseButton1Down:Connect(onMouseButtonPressed)

I don’t understand why it does not work

3 Likes

in order to change the cframe of the camera you need to set its type to scriptable before changing the cframe,
place this line of code before changing the cframe in the teleportCamera function:

camera.CameraType = Enum.CameraType.Scriptable
2 Likes

it still does not work, it does display this error:


and this is the code updated:

3 Likes

Try this:

local player = game.Players.LocalPlayer
local tool = script.Parent
local userInputService = game:GetService("UserInputService")

-- Function to teleport the camera to the Cam part's position
local function teleportCamera()
	local camera = game.Workspace.CurrentCamera
	local camPart = tool:FindFirstChild("cam") -- Move this line inside the function

	if camPart then
        camera.CameraType = Enum.CameraType.Scriptable
		camera.CFrame = CFrame.new(camPart.Position)
	end
end

-- Function to handle mouse button events
local function onInput(input)
	if input.UserInputType == Enum.UserInputType.MouseButton2 then -- Right mouse button
		teleportCamera()
	end
end

-- Connect the function to the mouse button pressed event
userInputService.InputBegan:Connect(onInput)
3 Likes

WOW, it worked. Thanks!
would it be possible to know if there’s a way to reset the camera back to where it was with another click, this is intended for a gun aiming down sights.

2 Likes

You’re welcome! You can reset the camera by setting its CameraType to Enum.CameraType.Custom. If you have any issues with that, create a new topic.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.