CurrentCamera follow Player's Mouse

https://gyazo.com/188cc41d35781ebe7bf2e914fd789113

I would like to achieve something like that, is there a way I could do that?
The parameters are as they follow:

  • I’d like the Camera to have limited sight, henceforth I don’t want the Player to be able to completely rotate their camera, only be able to look side to side and/or up and down slightly with margins.

Anything would help, thanks!

1 Like

I wrote this localscript just now to see if it was possible:

-- Change this if you want a wider or narrower range of view.
local maxRotation = 45
----------------------

local player = game:GetService("Players").LocalPlayer
local camera = workspace.CurrentCamera
local center, distFromCenter
local angles = Vector2.new(0, 0)
local max = Vector2.new(1, 1) * math.rad(maxRotation)
local yaw, pitch
-- Update the 'angles' every time mouse is moved.
game:GetService("UserInputService").InputChanged:Connect(function(input, gpe)
	if (not gpe and input.UserInputType == Enum.UserInputType.MouseMovement) then
		center = camera.ViewportSize / 2
		distFromCenter = Vector2.new(input.Position.X, input.Position.Y) - center
		angles = (distFromCenter / center) * max * -1
	end
end)

local dist
local baseCF
-- Clamp the camera inside the limits every render frame.
game:GetService("RunService"):BindToRenderStep("CameraPointer", Enum.RenderPriority.Camera.Value + 1, function()
	if (player.Character and player.Character:FindFirstChild("HumanoidRootPart") ~= nil) then
		-- approx position and lookvector of the player's head. Add a "*CFrame.Angles(...)" to the end if you want a different angle.
		baseCF = player.Character.HumanoidRootPart.CFrame * CFrame.new(0, 1.5, 0)
		-------------------------------------------------------------------------
		dist = (camera.CFrame.Position - camera.Focus.Position).Magnitude
		camera.CFrame = baseCF * CFrame.fromOrientation(angles.Y, angles.X, 0) * CFrame.new(0, 0, dist)
	end
end)

Basically it compares the 2d position of your mouse cursor to the viewport size to get your mouse’s distance from the center of the screen. Obtain a fraction from that and multiply it by the maximum angle you want. Then every frame set the camera to force it into those bounds.

5 Likes

Result:

That’s exactly what I’ve been looking for, however would there be a way to achieve something like that when the mouse is idle and no longer moving? As in, I’d like the camera to be floating in a sense.

Simply just start tweening the camera up and down the whole time in a while loop, this will create the effect

By that do you mean the Part or CurrentCamera?