PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Create a Gyroscopic Camera

Create a Gyroscopic Camera

Oct 19 2018, 4:44 PM PST

This example creates a camera that matches the player’s device orientation via the device’s gyroscope. The code to this example can be seen in this uncopylocked place.

Note that it relies on the device’s gravity vector to determine the initial orientation of the device (whether it is flipped upside down or not). To determine the initial orientation of the device, you can use the UserInputService/GetDeviceGravity function.

In order for this example to work as expected, it must be placed in a LocalScript and the user’s device must have an UserInputService/GyroscopeEnabled|gyroscope.

local userInputService = game:GetService("UserInputService")
local runService = game:GetService("RunService")
 
local currentRotation = CFrame.new(Vector3.new(0,5,0), Vector3.new(0,5,-1))
local lastInputFrame = nil
local upsideDown = false
 
wait()
 
local orientationSet = false
local function ChangeGravity(gravity)
    if not orientationSet then
   	 upsideDown = (gravity.Position.X < -.5 or gravity.Position.Z > .5)
 
   	 orientationSet = true
    end
end
 
local function ChangeRotation(rotation, rotCFrame)
    if orientationSet then
   	 if not lastInputFrame then
   		 lastInputFrame = rotCFrame
   	 end
 
   	 local delta = rotCFrame * lastInputFrame:inverse()
   	 local x,y,z = delta:toEulerAnglesXYZ()
   	 if upsideDown then
   		 delta = CFrame.Angles(-x, y, z)
   	 else
   		 delta = CFrame.Angles(x, -y, z)
   	 end
   	 currentRotation = currentRotation * delta
 
   	 lastInputFrame = rotCFrame
    end
end

local function UpdateCamera()
    local camera = game.Workspace.CurrentCamera
    camera.CoordinateFrame = currentRotation
    camera.Focus = CFrame.new(currentRotation * Vector3.new(0,0,-10))
end
 
if userInputService.GyroscopeEnabled then
	userInputService.DeviceGravityChanged:Connect(ChangeGravity)
	userInputService.DeviceRotationChanged:Connect(ChangeRotation)
	runService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, UpdateCamera)
end