So, Im working on this game and I need help with like when u move the mouse to a certain spot the camera tilts toward that spot. I am having trouble with this is someone able to help?
You need to use Mouse.UnitRay
which originates from the camera and points towards the mouse’s world position. Then, using CFrame.fromMatrix()
, you can make the camera face there:
local rs = game:GetService("RunService")
local mouse = game.Players.LocalPlayer:GetMouse()
local camera = workspace.CurrentCamera
local function cameraToMousePos(unitRay, position) --forlook vector
local lookVector = unityRay.Direction --the direction of the ray
local modelUpVector = Vector3.new(0, 1, 0) --unit vector, magnitude doesn't matter
local rightVector = lookVector:Cross(modelUpVector) --cross to get a perpendicular rightVector
local upVector = rightVector:Cross(lookVector) --same, but with upVecctor
return CFrame.fromMatrix(position, rightVector, upVector) --we only need to provide two vectors and a position
end
rs.RenderStepped:Connect(function() --every frame
camera.CFrame = cameraToMousePos(mouse.UnitRay, camera.CFrame.Position) --don't change the position, just orientation
end)
DM me if you want further explanation.
I hope that helps!
1 Like
What do you mean? If you mean that you want to make player’s camera face toward to the point where your mouse is pointing, then you will need to use LocalScript
,:GetMouse()
and CFrame.new(p1,p2)
.
Also you need Runservice
to refresh your camera’s CFrame.
local Service = game:GetService("RunService")
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Camera = game.Workspace.CurrentCamera
Service.RenderStepped:Connect(function()
Camera.CFrame = CFrame.new(Camera.CFrame.Position,Mouse.Hit.Position)
end)