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

GetDeviceGravity

This function returns an InputObject describing the device’s current gravity vector.

The gravity vector is determined by the device’s orientation relative to the real-world force of gravity. For instance, if a device is perfectly upright and vertical, the gravity vector would be DataType/Vector3|Vector3.new(0, 1, 0). Inverting the device so that it is perfectly upside-down and vertical would result in a gravity vector of Vector3.new(0, -1, 0).

This function might be used to enable the user’s device to impact or control gravity within the game or move in-game objects such as a ball.

Gravity is only tracked for players using a device with an enabled accelerometer - such as a mobile device.

To check if a user’s device has an enabled accelerometer, check the value of UserInputService/AccelerometerEnabled. If the device has an enabled accelerometer, you can also use the UserInputService/DeviceGravityChanged event to track when force of gravity on the user’s device changes.

As UserInputService is client-side only, this function can only be used in a LocalScript.

Returns

Return Type Summary

An InputObject that describes the device’s current gravity vector


Code Samples


Moving Objects with the Accelerometer

Using the Accelerometer gives us the down direction for the player’s device. We can use this to move objects in the game world. This example implements a level where the bubble will move along the Z axis depending on the device current accelerometer position in Z.

An uncopylocked version of this example can be seen here.

-- Make variable for UserInputService
local userInputService = game:GetService("UserInputService")
 
-- Make variables for game objects
local label = script.Parent
local bubble = game.Workspace.Bubble
local camera = game.Workspace.CurrentCamera
 
-- Fix camera above level
camera.CameraType = Enum.CameraType.Scriptable
camera.CoordinateFrame = CFrame.new(Vector3.new(0,20,0), Vector3.new(0,0,0))
 
-- Check if user's device supports accelerometer
if userInputService.AccelerometerEnabled then
	-- Bind event to when accelerometer detects change
	userInputService.DeviceGravityChanged:Connect(function(accel)
		-- Display accelerometer output to a TextLabel
		label.Text = string.format("%.2f", accel.Position.X) .. "\n" ..
					 string.format("%.2f", accel.Position.Y) .. "\n" ..
					 string.format("%.2f", accel.Position.Z)
		-- Move the bubble in the world based on the accelerometer data
		bubble.Position = Vector3.new(0, 1.8, - 8 * accel.Position.Z)
	end)
else
	-- Kindly turn away users who do not have an accelerometer
	local message = Instance.new("Message", game.Players.LocalPlayer.PlayerGui)
	message.Text = "This game only works on a device with an accelerometer."
end