UserInputService

Show Deprecated
Not Creatable
Service
Not Replicated

UserInputService is a service used to detect and capture the different types of input available on a user's device.

The primary purpose of this service is to allow for experiences to cooperate with multiple forms of available input, such as gamepads, touch screens, and keyboards. It allows a LocalScript to perform different actions depending on the device and, in turn, provide the best experience for the end user.

Some usages of this service include detecting user input when they interact with GUIs, tools, and other game instances. In order to detect user input, the service must look for a service event. For example, the service can detect events such as when the user touches the screen of a mobile device using UserInputService.TouchStarted, or connects a gamepad such as an Xbox controller to their device using UserInputService.GamepadConnected.

Since this service is client-side only, it will only work when used in a LocalScript or a ModuleScript required by a LocalScript. As UserInputService is client-side only, users in the game can only detect their own input - and not the input of others.

See also ContextActionService, a service which allows you to bind functions to multiple user inputs.

Code Samples

UserInputService

-- We must get the UserInputService before we can use it
local UserInputService = game:GetService("UserInputService")
-- A sample function providing one usage of InputBegan
local function onInputBegan(input, _gameProcessed)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed!")
end
end
UserInputService.InputBegan:Connect(onInputBegan)

Summary

Properties

  • Read Only
    Not Replicated
    Read Parallel

    Describes whether the user's device has an accelerometer.

  • Read Only
    Not Replicated
    Read Parallel

    Describes whether the device being used by a user has an available gamepad.

  • Read Only
    Not Replicated
    Read Parallel

    Describes whether the user's device has a gyroscope.

  • Read Only
    Not Replicated
    Read Parallel

    Describes whether the user's device has a keyboard available.

  • Determines whether the user's mouse can be moved freely or is locked.

  • Not Replicated
    Read Parallel

    Scales the delta (change) output of the user's Mouse.

  • Read Only
    Not Replicated
    Read Parallel

    Describes whether the user's device has a mouse available.

  • MouseIcon:ContentId
    Read Parallel

    The content ID of the image used as the user mouse icon.

  • Read Parallel

    Determines whether the Mouse icon is visible.

  • Read Only
    Not Replicated
    Read Parallel

    Determines the position of the on-screen keyboard.

  • Read Only
    Not Replicated
    Read Parallel

    Determines the size of the on-screen keyboard.

  • Read Only
    Not Replicated
    Read Parallel

    Describes whether an on-screen keyboard is currently visible on the user's screen.

  • Read Only
    Not Replicated
    Read Parallel

    Describes whether the user's current device has a touch-screen available.

  • Read Only
    Not Replicated
    Read Parallel

    Indicates whether the user is using a virtual reality headset.

Methods

Events

Properties

AccelerometerEnabled

Read Only
Not Replicated
Read Parallel

This property describes whether the user's device has an accelerometer

An accelerometer is a component found in most mobile devices that measures acceleration (change in speed).

For example, the following code snippet demonstrates how to check if the user's device has an accelerometer.


local UserInputService = game:GetService("UserInputService")
local accelerometerEnabled = UserInputService.AccelerometerEnabled
if accelerometerEnabled then
print("Accelerometer enabled!")
else
print("Accelerometer not enabled!")
end

If the device has an enabled accelerometer, you can get it's current acceleration by using the UserInputService:GetDeviceAcceleration() function or track when the device's acceleration changes by using the UserInputService.DeviceAccelerationChanged event.

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

Code Samples

Move a Ball using the Accelerometer

local Workspace = game:GetService("Workspace")
local UserInputService = game:GetService("UserInputService")
local ball = script.Parent:WaitForChild("Ball")
local mass = ball:GetMass()
local gravityForce = ball:WaitForChild("GravityForce")
local function moveBall(gravity)
gravityForce.Force = gravity.Position * Workspace.Gravity * mass
end
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceGravityChanged:Connect(moveBall)
end
Create a Gyroscopic Camera

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_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 HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end

GamepadEnabled

Read Only
Not Replicated
Read Parallel

This property describes whether the device being used by a user has an available gamepad. If gamepads are available, you can use UserInputService:GetConnectedGamepads() to retrieve a list of connected gamepads.

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

See also:

Code Samples

How to Set the Active Gamepad for Input

local UserInputService = game:GetService("UserInputService")
local function getActiveGamepad()
local activeGamepad = nil
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for _, gamepad in connectedGamepads do
if activeGamepad == nil or gamepad.Value < activeGamepad.Value then
activeGamepad = gamepad
end
end
end
if activeGamepad == nil then -- Nothing is connected; set up for "Gamepad1"
activeGamepad = Enum.UserInputType.Gamepad1
end
return activeGamepad
end
if UserInputService.GamepadEnabled then
local activeGamepad = getActiveGamepad()
print(activeGamepad)
end

GyroscopeEnabled

Read Only
Not Replicated
Read Parallel

This property describes whether the user's device has a gyroscope.

A gyroscope is a component found in most mobile devices that detects orientation and rotational speed.

If a user's device has a gyroscope, you can use incorporate it into your game using the UserInputService:GetDeviceRotation() function and UserInputService.DeviceRotationChanged event.


local UserInputService = game:GetService("UserInputService")
local gyroIsEnabled = UserInputService.GyroscopeEnabled
if gyroIsEnabled then
print("Gyroscope is enabled!")
else
print("Gyroscope is not enabled!")
end

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

Code Samples

Create a Gyroscopic Camera

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_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 HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end

KeyboardEnabled

Read Only
Not Replicated
Read Parallel

This property describes whether the user's device has a keyboard available. This property is true when the user's device has an available keyboard, and false when it does not.

It can be used to determine whether the user has an available keyboard - which can be important if you want to check if you can use UserInputService:IsKeyDown() or UserInputService:GetKeysPressed() to check for keyboard input.

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

Code Samples

Check if Keyboard is Enabled

local UserInputService = game:GetService("UserInputService")
if UserInputService.KeyboardEnabled then
print("The user's device has an available keyboard!")
else
print("The user's device does not have an available keyboard!")
end

MouseBehavior

Read Parallel

This property sets how the user's mouse behaves based on the Enum.MouseBehavior Enum. The default value is Enum.MouseBehavior.Default.

It can be set to three values:

  1. Default: The mouse moves freely around the user's screen.
  2. LockCenter: The mouse is locked, and cannot move from, the center of the user's screen.
  3. LockCurrentPosition: The mouse is locked, and cannot move from, it's current position on the user's screen at the time of locking.

The value of this property does not affect the sensitivity of events tracking mouse movement. For example, GetMouseDelta returns the same Vector2 screen position in pixels regardless of whether the mouse is locked or able to move freely around the user's screen. As a result, default scripts like those controlling the camera are not impacted by this property.

This property is overridden if a GuiButton with Modal enabled is GuiButton.Visible unless the player's right mouse button is down.

Note that, if the mouse is locked, UserInputService.InputChanged will still fire when the player moves the mouse and will pass in the Delta that the mouse attempted to move by. Additionally, if the player is kicked from the game, the mouse will be forcefully unlocked.

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

Code Samples

Create a Binoculars Script

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end
Create a Custom CameraScript

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end

MouseDeltaSensitivity

Not Replicated
Read Parallel

This property determines the sensitivity of the user's Mouse.

The sensitivity determines the extent to which a movement of the physical mouse translates to a movement of the mouse in-game. This can be used to adjusted how sensitive events tracking mouse movement, like GetMouseDelta, are to mouse movement.

This property does not affect the movement of the mouse icon. Nor does it affect the Camera Sensitivity setting found in the Settings tab of the client's Settings menu, which also adjusts the sensitivity of events tracking mouse movement.

This property has a maximum value of 10 and a minimum value of 0. A lower value corresponds to lower sensitivity, and a higher value to higher sensitivity.

When sensitivity is 0, events that track the mouse's movement will still fire but all parameters and properties indicating the change in mouse position will return Vector2.new(), or Vector3.new() in the case of InputObject.Delta. For example, GetMouseDelta will always return (0, 0).

Code Samples

Create a Binoculars Script

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end

MouseEnabled

Read Only
Not Replicated
Read Parallel

This property describes whether the user's device has a mouse available. This property is true when the user's device has an available mouse, and false when it does not.


local UserInputService = game:GetService("UserInputService")
if UserInputService.MouseEnabled then
print("The user's device has an available mouse!")
else
print("The user's device does not have an available mouse!")
end

It is important to check this before using UserInputService mouse functions such as UserInputService:GetMouseLocation().

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

See also:

Code Samples

Create a Binoculars Script

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end

MouseIcon

ContentId
Read Parallel

The MouseIcon property determines the image used as the pointer. If blank, a default arrow is used. While the cursor hovers over certain UI objects such as an ImageButton, TextButton, TextBox, or ProximityPrompt, this image will be overridden and temporarily ignored.

To hide the cursor entirely, do not use a transparent image. Instead, set UserInputService.MouseIconEnabled to false.

Code Samples

UserInputService.MouseIcon

local UserInputService = game:GetService("UserInputService")
-- In order to restore the cursor to what it was set to previously, it will need to be saved to a variable
local savedCursor = nil
local function setTemporaryCursor(cursor: string)
-- Only update the saved cursor if it's not currently saved
if not savedCursor then
savedCursor = UserInputService.MouseIcon
end
UserInputService.MouseIcon = cursor
end
local function clearTemporaryCursor()
-- Only restore the mouse cursor if there's a saved cursor to restore
if savedCursor then
UserInputService.MouseIcon = savedCursor
-- Don't restore the same cursor twice (might overwrite another script)
savedCursor = nil
end
end
setTemporaryCursor("http://www.roblox.com/asset?id=163023520")
print(UserInputService.MouseIcon)
clearTemporaryCursor()
print(UserInputService.MouseIcon)

MouseIconEnabled

Read Parallel

This property determines whether the Mouse icon is visible When true the mouse's icon is visible, when false it is not.

For example, the code snippet below hides the mouse's icon.


local UserInputService = game:GetService("UserInputService")
UserInputService.MouseIconEnabled = false

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

Code Samples

Hide Mouse During Keyboard Input

local UserInputService = game:GetService("UserInputService")
local mouseInput = {
Enum.UserInputType.MouseButton1,
Enum.UserInputType.MouseButton2,
Enum.UserInputType.MouseButton3,
Enum.UserInputType.MouseMovement,
Enum.UserInputType.MouseWheel,
}
local keyboard = Enum.UserInputType.Keyboard
local function toggleMouse(lastInputType)
if lastInputType == keyboard then
UserInputService.MouseIconEnabled = false
return
end
for _, mouse in pairs(mouseInput) do
if lastInputType == mouse then
UserInputService.MouseIconEnabled = true
return
end
end
end
UserInputService.LastInputTypeChanged:Connect(toggleMouse)

OnScreenKeyboardPosition

Read Only
Not Replicated
Read Parallel

This property describes the position of the on-screen keyboard in pixels. The keyboard's position is Vector2.new(0, 0) when it is not visible.

As UserInputService is client-side only, this property can only be used in a LocalScript, or a Script with RunContext set to Enum.RunContext.Client.

See also OnScreenKeyboardVisible and OnScreenKeyboardSize.

Code Samples

UserInputService.OnScreenKeyboardPosition

local UserInputService = game:GetService("UserInputService")
print(UserInputService.OnScreenKeyboardPosition)

OnScreenKeyboardSize

Read Only
Not Replicated
Read Parallel

This property describes the size of the on-screen keyboard in pixels. The keyboard's size is Vector2.new(0, 0) when it is not visible.

As UserInputService is client-side only, this property can only be used in a LocalScript, or a Script with RunContext set to Enum.RunContext.Client.

See also OnScreenKeyboardVisible and OnScreenKeyboardPosition.

OnScreenKeyboardVisible

Read Only
Not Replicated
Read Parallel

This property describes whether an on-screen keyboard is currently visible on the user's screen.

As UserInputService is client-side only, this property can only be used in a LocalScript, or a Script with RunContext set to Enum.RunContext.Client.

See also OnScreenKeyboardSize and OnScreenKeyboardPosition.

TouchEnabled

Read Only
Not Replicated
Read Parallel

This property describes whether the user's current device has a touch screen available.

The property is used to determine if the user's device has a touch screen, and therefore if touch events will fire. If TouchEnabled is true, you can use UserInputService events such as UserInputService.TouchStarted and UserInputService.TouchEnded to track when a user starts and stops touching the screen of their device.

The code snippet below prints whether the user's device has a touch screen.


local UserInputService = game:GetService("UserInputService")
if UserInputService.TouchEnabled then
print("The user's device has a touchscreen!")
else
print("The user's device does not have a touchscreen!")
end

See also:

Code Samples

Create a Custom CameraScript

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end

VREnabled

Read Only
Not Replicated
Read Parallel

This property describes whether the user is using a virtual reality (VR) device.

If a VR device is enabled, you can interact with its location and movement through functions such as UserInputService:GetUserCFrame(). You can also react to VR device movement using the UserInputService.UserCFrameChanged event.


local UserInputService = game:GetService("UserInputService")
local isUsingVR = UserInputService.VREnabled
if isUsingVR then
print("User is using a VR headset!")
else
print("User is not using a VR headset!")
end

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

See also:

Code Samples

VR Head Tracking

local VRService = game:GetService("VRService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local function TrackHead(inputType, value)
if inputType == Enum.UserCFrame.Head then
head.CFrame = value
end
end
if VRService.VREnabled then
-- Set the initial CFrame
head.CFrame = VRService:GetUserCFrame(Enum.UserCFrame.Head)
-- Track VR headset movement and mirror for character's head
VRService.UserCFrameChanged:Connect(TrackHead)
end

Methods

GamepadSupports

This function returns whether the given Enum.UserInputType gamepad supports a button corresponding with the given Enum.KeyCode. This function is used to determine valid gamepad inputs.

To determine which Enum.UserInputType gamepads are connected, use UserInputService:GetConnectedGamepads().

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

See also:

Parameters

gamepadNum: Enum.UserInputType

The Enum.UserInputType of the gamepad.

gamepadKeyCode: Enum.KeyCode

The Enum.KeyCode of the button in question.


Returns

Whether the given gamepad supports a button corresponding with the given Enum.KeyCode.

Code Samples

Binding Functions to Gamepad Controls

local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local controller = Enum.UserInputType.Gamepad1
local buttonX = Enum.KeyCode.ButtonX
local function isSupported(gamepad, keycode)
return UserInputService:GamepadSupports(gamepad, keycode)
end
local function action()
print("Action")
end
if isSupported(controller, buttonX) then
ContextActionService:BindAction("sample action", action, false, buttonX)
end

GetConnectedGamepads

This function returns an array of Enum.UserInputType gamepads currently connected. If no gamepads are connected, this array will be empty. Additionally, it only returns UserInputType objects that are gamepads. For instance, this event will return a connected Gamepad1 object but not a Keyboard object.

For example, the following code snippet retrieves the connected gamepads and stores them in a variable named connectedGamepads.


local UserInputService = game:GetService("UserInputService")
local connectedGamepads = UserInputService:GetConnectedGamepads()

To check if a specific gamepad is connected, use UserInputService:GetGamepadConnected().

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

See also:


Returns

An array of UserInputTypes corresponding with the gamepads connected to the user's device.

Code Samples

How to Set the Active Gamepad for Input

local UserInputService = game:GetService("UserInputService")
local function getActiveGamepad()
local activeGamepad = nil
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for _, gamepad in connectedGamepads do
if activeGamepad == nil or gamepad.Value < activeGamepad.Value then
activeGamepad = gamepad
end
end
end
if activeGamepad == nil then -- Nothing is connected; set up for "Gamepad1"
activeGamepad = Enum.UserInputType.Gamepad1
end
return activeGamepad
end
if UserInputService.GamepadEnabled then
local activeGamepad = getActiveGamepad()
print(activeGamepad)
end

GetDeviceAcceleration

The GetDeviceAcceleration function determines the current acceleration of the user's device. It returns an InputObject that describes the device's current acceleration.

In order for this to work, the user's device must have an enabled accelerometer. To check if a user's device has an enabled accelerometer, you can check the UserInputService.AccelerometerEnabled property.

If you want to track when the user's device's acceleration changes instead, you can use the UserInputService.DeviceAccelerationChanged event.

Since it only fires locally, it can only be used in a LocalScript.


Returns

Code Samples

Print Device Acceleration

local UserInputService = game:GetService("UserInputService")
local accelerometerEnabled = UserInputService.AccelerometerEnabled
if accelerometerEnabled then
local acceleration = UserInputService:GetDeviceAcceleration().Position
print(acceleration)
else
print("Cannot get device acceleration because device does not have an enabled accelerometer!")
end

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 (portrait), the gravity vector is Vector3.new(0, 0, -9.18). If the left side of the device is pointing down, the vector is Vector3.new(9.81, 0, 0). Finally, if the back of the device is pointing down, the vector is Vector3.new(0, -9.81, 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 gyroscope - such as a mobile device.

To check if a user's device has an enabled gyroscope, check the value of UserInputService.GyroscopeEnabled. If the device has an enabled gyroscope, 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

Code Samples

Moving Objects with the Gyroscope

local UserInputService = game:GetService("UserInputService")
local bubble = script.Parent:WaitForChild("Bubble")
local camera = workspace.CurrentCamera
camera.CameraType = Enum.CameraType.Scriptable
camera.CFrame = CFrame.new(0, 20, 0) * CFrame.Angles(-math.pi / 2, 0, 0)
if UserInputService.GyroscopeEnabled then
-- Bind event to when gyroscope detects change
UserInputService.DeviceGravityChanged:Connect(function(accel)
-- Move the bubble in the world based on the gyroscope data
bubble.Position = Vector3.new(-8 * accel.Position.X, 1.8, -8 * accel.Position.Z)
end)
end

GetDeviceRotation

This function returns an InputObject and a CFrame describing the device's current rotation vector.

This is fired with an InputObject. The Position property of the input object is a Enum.InputType.Gyroscope that tracks the total rotation in each local device axis.

Device rotation can only be tracked on devices with a gyroscope.

As this function fires locally, it can only be used in a LocalScript.


Returns

A tuple containing two properties:

  1. The delta property describes the amount of rotation that last happened
  2. The CFrame is the device's current rotation relative to its default reference frame.

Code Samples

Print Device Rotation

local UserInputService = game:GetService("UserInputService")
local gyroEnabled = UserInputService:GyroscopeEnabled()
if gyroEnabled then
local _inputObj, cframe = UserInputService:GetDeviceRotation()
print("CFrame: {", cframe, "}")
else
print("Cannot get device rotation because device does not have an enabled gyroscope!")
end

GetFocusedTextBox

This function returns the TextBox the client is currently focused on. A TextBox can be manually selected by the user, or selection can be forced using the TextBox:CaptureFocus() function. If no TextBox is selected, this function will return nil.

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

See also:


Returns

Code Samples

Ignore User Input When a TextBox Is Focused

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local jumpKey = Enum.KeyCode.J
local isJumping = false
local function InputBegan(input, _gameProcessedEvent)
local TextBoxFocused = UserInputService:GetFocusedTextBox()
-- Ignore input event if player is focusing on a TextBox
if TextBoxFocused then
return
end
-- Make player jump when user presses jumpKey Key on Keyboard
if input.UserInputType == Enum.UserInputType.Keyboard and input.KeyCode == jumpKey then
if not isJumping then
isJumping = true
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
end
end
local function StateChanged(_oldState, newState)
-- Prevent player from jumping again using jumpKey if already jumping
if newState == Enum.HumanoidStateType.Jumping then
isJumping = true
-- Allow player to jump again after landing
elseif newState == Enum.HumanoidStateType.Landed then
isJumping = false
end
end
UserInputService.InputBegan:Connect(InputBegan)
humanoid.StateChanged:Connect(StateChanged)

GetGamepadConnected

This function returns whether a gamepad with the given Enum.UserInputType is connected to the client.

This can be used to check if a specific gamepad, such as 'Gamepad1' is connected to the client's device.

To retrieve a list of all connected gamepads, use UserInputService:GetConnectedGamepads().

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

See also:

Parameters

gamepadNum: Enum.UserInputType

The Enum.UserInputType of the gamepad in question.


Returns

Whether a gamepad associated with Enum.UserInputType is connected.

Code Samples

Check Whether a Gamepad is Connected

local UserInputService = game:GetService("UserInputService")
local isConnected = UserInputService:GetGamepadConnected(Enum.UserInputType.Gamepad1)
if isConnected then
print("Gamepad1 is connected to the client")
else
print("Gamepad1 is not connected to the client")
end

GetGamepadState

This function returns an array of InputObjects for all available inputs on the given Enum.UserInputType gamepad, representing each input's last input state.

To find the UserInputTypes of connected gamepads, use UserInputService:GetConnectedGamepads().

As this function only fires locally, it can only be used in a LocalScript.

See also:

Parameters

gamepadNum: Enum.UserInputType

The Enum.UserInputType corresponding with the gamepad in question.


Returns

An array of InputObjects representing the current state of all available inputs for the given gamepad.

GetImageForKeyCode

ContentId

This method takes the requested Enum.KeyCode and returns the associated image for the currently connected gamepad device (limited to Xbox, PlayStation and Windows). This means that if the connected controller is an Xbox One controller, the user sees Xbox assets. Similarly, if the connected device is a PlayStation controller, the user sees PlayStation assets. If you want to use custom assets, see GetStringForKeyCode().

Parameters

keyCode: Enum.KeyCode

The Enum.KeyCode for which to fetch the associated image.


Returns

ContentId

The returned image asset ID.

Code Samples

UserInputService - Get Image For KeyCode

local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappedIconImage = UserInputService:GetImageForKeyCode(key)
imageLabel.Image = mappedIconImage

GetKeysPressed

This function returns an array of InputObjects associated with the keys currently being pressed down.

This array can be iterated through to determine which keys are currently being pressed, using the InputObject.KeyCode values.

To check if a specific key is being pressed, use UserInputService:IsKeyDown().

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


Returns

An array of InputObjects associated with the keys currently being pressed.

Code Samples

Double Jump Key Combo

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local actionKey = Enum.KeyCode.LeftShift
local canJump = true
local canDoubleJump = false
local function jumpRequest()
local keysPressed = UserInputService:GetKeysPressed()
for _, key in ipairs(keysPressed) do
if key.KeyCode == actionKey and canJump then
canJump = false
canDoubleJump = true
end
end
end
local function stateChanged(oldState, newState)
-- Double jump during freefall if able to
if oldState == Enum.HumanoidStateType.Jumping and newState == Enum.HumanoidStateType.Freefall and canDoubleJump then
canDoubleJump = false
task.wait(0.2)
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
-- Allow player to jump again after they land
if oldState == Enum.HumanoidStateType.Freefall and newState == Enum.HumanoidStateType.Landed then
canJump = true
end
end
UserInputService.JumpRequest:Connect(jumpRequest)
humanoid.StateChanged:Connect(stateChanged)

GetLastInputType

This function returns 'Enum.UserInputType` associated with the user's most recent input.

For example, if the user's previous input had been pressing the spacebar, the Enum.UserInputType returned would be 'Keyboard'.

The UserInputService.LastInputTypeChanged event can be used to track when the last Enum.UserInputType used by the user changes.

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


Returns

The Enum.UserInputType associated with the user's most recent input.

Code Samples

UserInputService:GetLastInputType

local UserInputService = game:GetService("UserInputService")
local lastInput = UserInputService:GetLastInputType()
if lastInput == Enum.UserInputType.Keyboard then
print("Most recent input was via keyboard")
end

GetMouseButtonsPressed

This function returns an array of InputObjects corresponding to the mouse buttons currently being pressed down.

Mouse buttons that are tracked by this function include:

Name Description
MouseButton1The left mouse button.
MouseButton2The right mouse button.
MouseButton3The middle mouse button.

If the user is not pressing any mouse button down when the function is called, it will return an empty array.

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


Returns

An array of InputObjects corresponding to the mouse buttons currently being currently held down.

Code Samples

Check which MouseButtons are Pressed

local UserInputService = game:GetService("UserInputService")
-- InputBegan is a UserInputService event that fires when the player
-- begins interacting via a Human-User input device
UserInputService.InputBegan:Connect(function(_input, _gameProcessedEvent)
-- Returns an array of the pressed MouseButtons
local buttons = UserInputService:GetMouseButtonsPressed()
local m1Pressed, m2Pressed = false, false
for _, button in pairs(buttons) do
if button.UserInputType.Name == "MouseButton1" then
print("MouseButton1 is pressed")
m1Pressed = true
end
if button.UserInputType.Name == "MouseButton2" then
print("MouseButton2 is pressed")
m2Pressed = true
end
if m1Pressed and m2Pressed then
print("Both mouse buttons are pressed")
end
end
end)

GetMouseDelta

This function returns the change, in pixels, of the position of the player's Mouse in the last rendered frame as a Vector2. This function only works if the mouse has been locked using the UserInputService.MouseBehavior property. If the mouse has not been locked, the returned Vector2 values will be zero.

The sensitivity of the mouse, determined in the client's settings and UserInputService.MouseDeltaSensitivity, will influence the result.

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


Returns

Change in movement of the mouse.

Code Samples

Getting Mouse Delta

local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local function OnRenderStep()
local delta = UserInputService:GetMouseDelta()
print("The mouse has moved", delta, "since the last step.")
end
RunService:BindToRenderStep("MeasureMouseMovement", Enum.RenderPriority.Input.Value, OnRenderStep)
Create a Custom CameraScript

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end

GetMouseLocation

This function returns a Vector2 representing the current screen location of the player's Mouse in pixels relative to the top left corner. This does not account for the GuiObject inset.

If the location of the mouse pointer is offscreen or the player's device does not have a mouse, the returned value will be undetermined.

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


Returns

A Vector2 representing the current screen location of the mouse, in pixels.

Code Samples

Move GUI To Mouse Location

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local gui = script.Parent
local screenGui = gui.Parent
screenGui.IgnoreGuiInset = true
local function moveGuiToMouse()
local mouseLocation = UserInputService:GetMouseLocation()
gui.Position = UDim2.fromOffset(mouseLocation.X, mouseLocation.Y)
end
moveGuiToMouse()
RunService:BindToRenderStep("moveGuiToMouse", 1, moveGuiToMouse)

GetNavigationGamepads

This function returns an array of gamepad UserInputTypes that are connected and enabled for GUI navigation. This list is in descending order of priority, meaning it can be iterated over to determine which gamepad should have navigation control.

Whether a connected gamepad is a navigation gamepad only determines which gamepad(s) control the navigation GUIs. This does not influence navigation controls.

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

See also:


Returns

An array of UserInputTypes that can be used for GUI navigation, in descending order of priority.

GetStringForKeyCode

GetStringForKeyCode returns a string representing a key the user should press in order to input a given Enum.KeyCode, keeping in mind their keyboard layout. For key codes that require some modifier to be held, this function returns the key to be pressed in addition to the modifier. See the examples below for further explanation.

When using Roblox with a non‑QWERTY keyboard layout, key codes are mapped to equivalent QWERTY positions. For example, pressing A on an AZERTY keyboard results in Enum.KeyCode.Q. This mapping can lead to mismatched information on experience UI elements. For example, "Press M to open the map" is inaccurate on an AZERTY keyboard; it would need to be "Press ? to open the map" which is in the same position as M on QWERTY. This function solves this issue by providing the actual key to be pressed while using non‑QWERTY keyboard layouts.


local UserInputService = game:GetService("UserInputService")
local textLabel = script.Parent
local mapKey = Enum.KeyCode.M
textLabel.Text = "Press " .. UserInputService:GetStringForKeyCode(mapKey) .. " to open the map"

Examples on QWERTY Keyboard

KeyCodeReturn Value
Enum.KeyCode.QQ
Enum.KeyCode.WW
Enum.KeyCode.Equals=
Enum.KeyCode.At2 because @ is typed with Shift2

Examples on AZERTY Keyboard

Gamepad Usage

GetStringForKeyCode() returns the string mapping for the Enum.KeyCode for the most recently connected gamepad. If the connected controller is not supported, the function returns the default string conversion for the requested key code.

The following example shows how you can map custom assets for ButtonA:


local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappings = {
ButtonA = "rbxasset://BUTTON_A_ASSET", -- Replace with the desired ButtonA asset
ButtonCross = "rbxasset://BUTTON_CROSS_ASSET" -- Replace with the desired ButtonCross asset
}
local mappedKey = UserInputService:GetStringForKeyCode(key)
local image = mappings[mappedKey]
imageLabel.Image = image

Gamepad Mappings

The directional pad key codes do not have any differences based on device. Enum.KeyCode.ButtonSelect has slightly different behavior in some cases. Use both PlayStation mappings to ensure users see the correct buttons.

KeyCodePlayStation Return ValueXbox Return Value
Enum.KeyCode.ButtonAButtonCrossButtonA
Enum.KeyCode.ButtonBButtonCircleButtonB
Enum.KeyCode.ButtonXButtonSquareButtonX
Enum.KeyCode.ButtonYButtonTriangleButtonY
Enum.KeyCode.ButtonL1ButtonL1ButtonLB
Enum.KeyCode.ButtonL2ButtonL2ButtonLT
Enum.KeyCode.ButtonL3ButtonL3ButtonLS
Enum.KeyCode.ButtonR1ButtonR1ButtonRB
Enum.KeyCode.ButtonR2ButtonR2ButtonRT
Enum.KeyCode.ButtonR3ButtonR3ButtonRS
Enum.KeyCode.ButtonStartButtonOptionsButtonStart
Enum.KeyCode.ButtonSelectButtonTouchpad and ButtonShareButtonSelect

System Images for KeyCodes

When using a Enum.KeyCode that may be better represented as an image, such as for an ImageLabel in a user interface, you can use the following legacy icons. However, it's recommended that you use GetImageForKeyCode() as a more modern, cross‑platform method to retrieve Xbox and PlayStation controller icons.

KeyCodeImageAsset ID
Enum.KeyCode.ButtonXrbxasset://textures/ui/Controls/xboxX.png
Enum.KeyCode.ButtonYrbxasset://textures/ui/Controls/xboxY.png
Enum.KeyCode.ButtonArbxasset://textures/ui/Controls/xboxA.png
Enum.KeyCode.ButtonBrbxasset://textures/ui/Controls/xboxB.png
Enum.KeyCode.DPadLeftrbxasset://textures/ui/Controls/dpadLeft.png
Enum.KeyCode.DPadRightrbxasset://textures/ui/Controls/dpadRight.png
Enum.KeyCode.DPadUprbxasset://textures/ui/Controls/dpadUp.png
Enum.KeyCode.DPadDownrbxasset://textures/ui/Controls/dpadDown.png
Enum.KeyCode.ButtonSelectrbxasset://textures/ui/Controls/xboxView.png
Enum.KeyCode.ButtonStartrbxasset://textures/ui/Controls/xboxmenu.png
Enum.KeyCode.ButtonL1rbxasset://textures/ui/Controls/xboxLB.png
Enum.KeyCode.ButtonR1rbxasset://textures/ui/Controls/xboxRB.png
Enum.KeyCode.ButtonL2rbxasset://textures/ui/Controls/xboxLT.png
Enum.KeyCode.ButtonR2rbxasset://textures/ui/Controls/xboxRT.png
Enum.KeyCode.ButtonL3rbxasset://textures/ui/Controls/xboxLS.png
Enum.KeyCode.ButtonR3rbxasset://textures/ui/Controls/xboxRS.png
Enum.KeyCode.Thumbstick1rbxasset://textures/ui/Controls/xboxLSDirectional.png
Enum.KeyCode.Thumbstick2rbxasset://textures/ui/Controls/xboxRSDirectional.png
Enum.KeyCode.Backspacerbxasset://textures/ui/Controls/backspace.png
Enum.KeyCode.Returnrbxasset://textures/ui/Controls/return.png
Enum.KeyCode.LeftShiftrbxasset://textures/ui/Controls/shift.png
Enum.KeyCode.RightShiftrbxasset://textures/ui/Controls/shift.png
Enum.KeyCode.Tabrbxasset://textures/ui/Controls/tab.png
Enum.KeyCode.Apostropherbxasset://textures/ui/Controls/apostrophe.png
Enum.KeyCode.Commarbxasset://textures/ui/Controls/comma.png
Enum.KeyCode.Backquoterbxasset://textures/ui/Controls/graveaccent.png
Enum.KeyCode.Periodrbxasset://textures/ui/Controls/period.png
Enum.KeyCode.Spacerbxasset://textures/ui/Controls/spacebar.png

Parameters

keyCode: Enum.KeyCode

Returns

GetSupportedGamepadKeyCodes

This function returns an array of KeyCodes that the gamepad associated with the given Enum.UserInputType supports.

This function can be used to determine which KeyCodes are supported and not supported by a connected gamepad. To determine if a specific KeyCode is supported, use UserInputService:GamepadSupports().

If called on a non existent, or non connected, gamepad, this function will return an empty array.

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

See also:

Parameters

gamepadNum: Enum.UserInputType

The Enum.UserInputType of the gamepad.


Returns

An array of KeyCodes supported by the given gamepad.

Code Samples

Binding Supported Gamepad KeyCodes

local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local function actionHandler(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
print("Action Handler: " .. actionName)
print(inputObject)
end
-- Since this function does not return anything, this handler will
-- "sink" the input and no other action handlers will be called after
-- this one.
end
local navGamepads = UserInputService:GetNavigationGamepads()
for _, gamepad in pairs(navGamepads) do
local supportedKeyCodes = UserInputService:GetSupportedGamepadKeyCodes(gamepad)
for _, keycode in pairs(supportedKeyCodes) do
if keycode == Enum.KeyCode.ButtonX then
ContextActionService:BindAction("SampleAction", actionHandler, false, Enum.KeyCode.ButtonX)
end
if keycode == Enum.KeyCode.X then
ContextActionService:BindAction("SampleAction", actionHandler, false, Enum.KeyCode.X)
end
end
end

IsGamepadButtonDown

This function checks if a particular button is pressed on a particular gamepad. It returns true if the gamepad has the specified button pressed down, otherwise it returns false.

Valid UserInputTypes

The specified gamepad should be one of the following UserInputType enum values:

Name
Enum.UserInputType.Gamepad1-8

Valid KeyCodes

The specified button should be one of the following KeyCodes enum values:

Name
Enum.KeyCode.ButtonX
Enum.KeyCode.ButtonY
Enum.KeyCode.ButtonA
Enum.KeyCode.ButtonB
Enum.KeyCode.ButtonR1
Enum.KeyCode.ButtonL1
Enum.KeyCode.ButtonR2
Enum.KeyCode.ButtonL2
Enum.KeyCode.ButtonR3
Enum.KeyCode.ButtonL3
Enum.KeyCode.ButtonStart
Enum.KeyCode.ButtonSelect
Enum.KeyCode.DPadLeft
Enum.KeyCode.DPadRight
Enum.KeyCode.DPadUp
Enum.KeyCode.DPadDown

This can be used to check whether a specific button, such as A, is being held down. For example:


local UserInputService = game:GetService("UserInputService")
local button = Enum.KeyCode.ButtonA
local gamepad = Enum.UserInputType.Gamepad1
local isButtonHeld = UserInputService:IsGamepadButtonDown(gamepad, button)

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

See also:

Parameters

gamepadNum: Enum.UserInputType

The Enum.UserInputType of the given gamepad.

gamepadKeyCode: Enum.KeyCode

The Enum.KeyCode of the specified button.


Returns

Whether the specified gamepad button on the given gamepad is pressed is pressed.

Code Samples

Special Action on Gamepad Button Combo

local UserInputService = game:GetService("UserInputService")
local activeGamepad = nil
local buttonX = Enum.KeyCode.ButtonX
local function isGamepadXDown()
if activeGamepad then
return UserInputService:IsGamepadButtonDown(activeGamepad, buttonX)
end
return false
end
local function input(_input, _gameProcessedEvent)
if not isGamepadXDown() then
-- Normal event
else
-- X Button down event
end
end
local function getActiveGamepad()
local activateGamepad = nil
local navigationGamepads = {}
navigationGamepads = UserInputService:GetNavigationGamepads()
if #navigationGamepads > 1 then
for i = 1, #navigationGamepads do
if activateGamepad == nil or navigationGamepads[i].Value < activateGamepad.Value then
activateGamepad = navigationGamepads[i]
end
end
else
local connectedGamepads = {}
connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for i = 1, #connectedGamepads do
if activateGamepad == nil or connectedGamepads[i].Value < activateGamepad.Value then
activateGamepad = connectedGamepads[i]
end
end
end
if activateGamepad == nil then -- nothing is connected, at least set up for gamepad1
activateGamepad = Enum.UserInputType.Gamepad1
end
end
return activateGamepad
end
if UserInputService.GamepadEnabled then
activeGamepad = getActiveGamepad()
UserInputService.InputBegan:Connect(input)
end

IsKeyDown

This function returns whether the user is holding down the key associated with the given Enum.KeyCode. It returns true if the specified key is pressed or false if it is not pressed.

This can be used to check if a specific key, such as the space bar, is being pressed. For example:


local UserInputService = game:GetService("UserInputService")
local spaceHeld = UserInputService:IsKeyDown(Enum.KeyCode.Space)

To retrieve a list of all keys pressed by the user, use the UserInputService:GetKeysPressed() function.

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

See also:

Parameters

keyCode: Enum.KeyCode

The Enum.KeyCode of the key.


Returns

Whether the specified key is being held down.

Code Samples

Special Action on Key Combo Press

local UserInputService = game:GetService("UserInputService")
local shiftKeyL = Enum.KeyCode.LeftShift
local shiftKeyR = Enum.KeyCode.RightShift
-- Return whether left or right shift keys are down
local function isShiftKeyDown()
return UserInputService:IsKeyDown(shiftKeyL) or UserInputService:IsKeyDown(shiftKeyR)
end
-- Handle user input began differently depending on whether a shift key is pressed
local function input(_input, _gameProcessedEvent)
if not isShiftKeyDown() then
-- Normal input
else
-- Shift input
end
end
UserInputService.InputBegan:Connect(input)

IsMouseButtonPressed

This function takes a mouse button Enum.UserInputType and returns a bool that indicates whether it is currently pressed.

The mouse button checked depends on the Enum.UserInputType value passed to the function as an argument. For example:


local UserInputService = game:GetService("UserInputService")
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)

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

Parameters

mouseButton: Enum.UserInputType

The Enum.UserInputType of the mouse button.


Returns

Whether the given mouse button is currently held down.

Code Samples

Create a Custom CameraScript

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end

IsNavigationGamepad

This function returns true if the specified Enum.UserInputType gamepad is allowed to control Navigation and Selection GuiObjects.

If you want to set a navigation gamepad, you can use UserInputService:SetNavigationGamepad(). You can also use UserInputService:GetNavigationGamepads() to get a list of all navigation gamepads.

For example, the code below checks if the gamepad1 is as a navigation gamepad:


local UserInputService = game:GetService("UserInputService")
if UserInputService:IsNavigationGamepad(UserInputType.Gamepad1) then
print("Gamepad is a navigation gamepad!")
else
print("Gamepad is not a navigation gamepad!")
end

A list of all connected gamepads, regardless of navigation can be retrieved using`UserInput/GetConnectedGamepads.

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

See also:

Parameters

gamepadEnum: Enum.UserInputType

The Enum.UserInputType of the specified gamepad.


Returns

Whether the specified gamepad is a navigation gamepad.

RecenterUserHeadCFrame

void

This function recenters the CFrame of the VR headset to the current orientation of the headset worn by the user. This means that the headset's current orientation is set to CFrame.new().

Use this function to move the headset CFrame to the center of the play area if it seems to be at a weird offset.

This behaves identically to the VRService function, VRService:RecenterUserHeadCFrame().

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


Returns

void

Code Samples

UserInputService:RecenterUserHeadCFrame

local UserInputService = game:GetService("UserInputService")
UserInputService:RecenterUserHeadCFrame()

SetNavigationGamepad

void

The SetNavigationGamepad function sets whether the specified Enum.UserInputType gamepad can move the GUI navigator. A gamepad that is allowed to move the GUI navigator is considered a navigation gamepad.

If the enabled argument is passed as true, the Gamepad can move the GUI navigator. If the argument is false, the Gamepad can not move the GUI navigator.

If you want to check if a specified Gamepad is a set to be a navigation gamepad, you can use the UserInputService:IsNavigationGamepad() function. You can also use the UserInputService:GetNavigationGamepads() to retrieve a list of all navigation gamepads.

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

See also:

Parameters

gamepadEnum: Enum.UserInputType

The Enum.UserInputType of the specified gamepad.

enabled: bool

Whether the specified gamepad can move the GUI navigator.


Returns

void

Code Samples

UserInputService:SetNavigationGamepad

local UserInputService = game:GetService("UserInputService")
UserInputService:SetNavigationGamepad(Enum.UserInputType.Gamepad1, true)

Events

DeviceAccelerationChanged

The DeviceAccelerationChanged event fires when a user moves a device that has an accelerometer.

An accelerometer is a component found in most mobile devices that measures acceleration (change in speed).

To determine whether a user's device has an accelerometer enabled, seeUserInputService.AccelerometerEnabled.

This event can be used to track the movement of a device that has an accelerometer. A sample usage includes moving the player character when a mobile device accelerates.

Additionally, this event can be used along with UserInputService:GetDeviceAcceleration() to determine the current movement of a user's device if the device has an accelerometer.

This event only fires locally - which means that only the player whose device moves can use the event and it will only work in a LocalScript.

Parameters

acceleration: InputObject

An InputObject, with a UserInputType of 'Accelerometer', and Position that shows the force of gravity on each local device axis.


Code Samples

Control Players Using the Accelerometer

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local SENSITIVITY = 0.2
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local ready = true
local function changeAcceleration(acceleration)
if ready then
ready = false
local accel = acceleration.Position
if accel.Y >= SENSITIVITY then
humanoid.Jump = true
end
if accel.Z <= -SENSITIVITY then
humanoid:Move(Vector3.new(-1, 0, 0))
end
if accel.Z >= SENSITIVITY then
humanoid:Move(Vector3.new(1, 0, 0))
end
if accel.X <= -SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, 1))
end
if accel.X >= SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, -1))
end
task.wait(1)
ready = true
end
end
UserInputService.DeviceAccelerationChanged:Connect(changeAcceleration)

DeviceGravityChanged

The UserInputService.DeviceGravityChanged event fires when the device's gravity Vector3 changes on a device that has an accelerometer.

A device's gravity vector represent the force of gravity on each of the device's X, Y, and Z axes. While gravity never changes, the force it exerts on each axis changes when the device rotates and changes orientation. The force value exerted on each axis is a unit vector ranging from -1 to 1.

An accelerometer is a component found in most mobile devices that measures acceleration (change in speed).

This event can be used to determine the real-world direction of the force of gravity on a user's device. This even can then be used to simulate the force of gravity on a user's device within the game, such as on in-game objects (see example below).

To check if a user's device has an enabled accelerometer, see UserInputService.AccelerometerEnabled. If the device has an enabled accelerometer, you can use the UserInputService:GetDeviceGravity() function to get the current force of gravity on the user's device.

Parameters

gravity: InputObject

An InputObject, with a InputObject.Position property that shows the force of gravity on each local device axis. This position can be used as a direction to determine the direction of gravity relative to the device.


Code Samples

Move a Ball using the Accelerometer

local Workspace = game:GetService("Workspace")
local UserInputService = game:GetService("UserInputService")
local ball = script.Parent:WaitForChild("Ball")
local mass = ball:GetMass()
local gravityForce = ball:WaitForChild("GravityForce")
local function moveBall(gravity)
gravityForce.Force = gravity.Position * Workspace.Gravity * mass
end
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceGravityChanged:Connect(moveBall)
end
Create a Gyroscopic Camera

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_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 HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end

DeviceRotationChanged

The DeviceRotationChanged event fires when a user rotates a device that has a gyroscope.

A gyroscope is a component found in most mobile devices that detects orientation and rotational speed.

The event is useful when tracking the orientation of the device and how changes as the user rotates their device. To determine the current device rotation, you can use the UserInputService:GetDeviceRotation() function.

To check if a user's device has an enabled gyroscope, and that this event will fire, see UserInputService.GyroscopeEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

Parameters

rotation: InputObject

An InputObject providing info about the device's rotation. InputObject.Position represents the new rotation a Vector3 positional value and InputObject.Delta represents the change in rotation in a Vector3 positional value.

cframe: CFrame

A CFrame representing the device's current orientation.


Code Samples

Create a Gyroscopic Camera

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_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 HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end
Move a Ball using the Accelerometer

local Workspace = game:GetService("Workspace")
local UserInputService = game:GetService("UserInputService")
local ball = script.Parent:WaitForChild("Ball")
local mass = ball:GetMass()
local gravityForce = ball:WaitForChild("GravityForce")
local function moveBall(gravity)
gravityForce.Force = gravity.Position * Workspace.Gravity * mass
end
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceGravityChanged:Connect(moveBall)
end

GamepadConnected

The GamepadConnected event fires when a gamepad is connected to the client.

Since a Roblox game supports multiple controllers, this event is useful when paired with the UserInputService.GamepadDisconnected event to track which controllers/gamepads are active. You can also use UserInputService:GetConnectedGamepads() to find the correct gamepad to use.

The following example demonstrates a usage example of a tracking when a gamepad is connected to the client.


local UserInputService = game:GetService("UserInputService")
local function GamepadConnected(gamepad)
print("Player has plugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadConnected:Connect(GamepadConnected)

If you want to see which devices are connected, you can use the UserInputService:GetConnectedGamepads() function.

As this event fires locally, it can only be used in a LocalScript.

See also:

Parameters

gamepadNum: Enum.UserInputType

The Enum.UserInputType of the connected gamepad.


GamepadDisconnected

The GamepadDisconnected event fires when a gamepad is disconnected.

Since a Roblox game supports multiple controllers, this event is useful when paired with the UserInputService.GamepadConnected event to track which controllers/gamepads are active. You can also use UserInputService:GetConnectedGamepads() to find the correct gamepad to use.

The following example demonstrates a usage example of a tracking when a gamepad is disconnected from the client.


local UserInputService = game:GetService("UserInputService")
local function GamepadDisconnected(gamepad)
print("Player has unplugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadDisconnected:Connect(GamepadDisconnected)

As this event fires locally, it can only be used in a LocalScript.

See also:

Parameters

gamepadNum: Enum.UserInputType

TheEnum.UserInputType of the disconnected gamepad.


InputBegan

The InputBegan event fires when a user begins interacting via a Human-Computer Interface device (mouse button down, touch begin, keyboard button down, etc.).

It can be used to track the beginning of user interaction, such as when a user first interacts with a GUI element, a gamepad, etc. It does not capture mouse wheel movements.

This event can be used along with UserInputService.InputChanged and UserInputService.InputEnded to track when user input begins, changes, and ends.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

Parameters

An InputObject instance, which contains information about the user's input.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Handling InputBegan

-- In order to use the InputBegan event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- A sample function providing multiple usage cases for various types of user input
UserInputService.InputBegan:Connect(function(input, gameProcessed)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key is being pushed down! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has started at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button is being pressed on a gamepad! Button:", input.KeyCode)
end
if gameProcessed then
print("The game engine internally observed this input!")
else
print("The game engine did not internally observe this input!")
end
end)

InputChanged

The InputChanged event fires when a user changes how they're interacting via a Human-Computer Interface device (mouse button down, touch begin, keyboard button down, etc).

To ignore events that are automatically handled by Roblox, like scrolling in a ScrollingFrame, check the gameProcessedEvent argument is false. This event can be used along with UserInputService.InputBegan and UserInputService.InputEnded to track when user input begins, changes, and ends.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

Parameters

An InputObject instance, which contains information about the user's input.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Handling InputChanged

-- In order to use the InputChanged event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- Prints the current input position and the change (delta) in position
local function printMovement(input)
print("Position:", input.Position)
print("Movement Delta:", input.Delta)
end
-- A sample function providing multiple usage cases for various types of user input
local function InputChanged(input, _gameProcessed)
if input.UserInputType == Enum.UserInputType.MouseMovement then
print("The mouse has been moved!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
print("The mouse wheel has been scrolled!")
print("Wheel Movement:", input.Position.Z)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
if input.KeyCode == Enum.KeyCode.Thumbstick1 then
print("The left thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.Thumbstick2 then
print("The right thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.ButtonL2 then
print("The pressure being applied to the left trigger has changed!")
print("Pressure:", input.Position.Z)
elseif input.KeyCode == Enum.KeyCode.ButtonR2 then
print("The pressure being applied to the right trigger has changed!")
print("Pressure:", input.Position.Z)
end
elseif input.UserInputType == Enum.UserInputType.Touch then
print("The user's finger is moving on the screen!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.Gyro then
local _rotInput, rotCFrame = UserInputService:GetDeviceRotation()
local rotX, rotY, rotZ = rotCFrame:toEulerAnglesXYZ()
local rot = Vector3.new(math.deg(rotX), math.deg(rotY), math.deg(rotZ))
print("The rotation of the user's mobile device has been changed!")
print("Position", rotCFrame.p)
print("Rotation:", rot)
elseif input.UserInputType == Enum.UserInputType.Accelerometer then
print("The acceleration of the user's mobile device has been changed!")
printMovement(input)
end
end
UserInputService.InputChanged:Connect(InputChanged)

InputEnded

The InputEnded event fires when a user stops interacting via a Human-Computer Interface device (mouse button down, touch begin, keyboard button down, etc). This is useful when tracking when a user releases a keyboard key, mouse button, touchscreen input, etc.

This event can be used along with UserInputService.InputBegan and UserInputService.InputChanged to track when user input begins, changes, and ends.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

Parameters

An InputObject instance, which contains information about the user input.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Handling InputEnded

-- In order to use the InputChanged event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- A sample function providing multiple usage cases for various types of user input
UserInputService.InputEnded:Connect(function(input, gameProcessed)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key has been released! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button has been released on a gamepad! Button:", input.KeyCode)
end
if gameProcessed then
print("The game engine internally observed this input!")
else
print("The game engine did not internally observe this input!")
end
end)

JumpRequest

The UserInputService JumpRequest event fires when there is a jump request from the client, for example when the client presses the spacebar or jump button on mobile.

This event fires whenever the user tries to make their Player.Character jump. Default behavior responds to a jump request by setting the player's Humanoid.Jump property to true, which makes the player's character jump.

The event can be used to track every time a player wants to jump. Instead of using it to make a player jump, this should be used to change default jump behavior - such as disabling jumping.

For example, the code below prints "Jump" every time the player sends a jump request.


local UserInputService = game:GetService("UserInputService")
function onJumpRequest()
print("Jump!")
end
UserInputService.JumpRequest:Connect(onJumpRequest)

Since this event fires multiple times for a single jump request, using a debounce is suggested.

If you would like to connect keys or buttons to other actions, consider using events such as UserInputService:GetKeysPressed() and UserInputService.InputBegan or the ContextActionService.

As this event only fires locally, it can only be used in a LocalScript.


Code Samples

Disable Jumping

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
-- Fires when the user tries to jump
local function jump()
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
end
UserInputService.JumpRequest:Connect(jump)

LastInputTypeChanged

The UserInputService.LastInputTypeChanged event fires whenever the client changes how they are interacting via a Human-Computer Interface device. (i.e. from MouseMovement to MouseWheel or from Thumbstick1 to Thumbstick2).

To get the value of the last input type, regardless of whether it has changed, you can use the UserInputService:GetLastInputType() function.

As this event only fires locally, it can only be used in a LocalScript.

Parameters

lastInputType: Enum.UserInputType

A Enum.UserInputType indicating the last input type.


Code Samples

Hide Mouse During Keyboard Input

local UserInputService = game:GetService("UserInputService")
local mouseInput = {
Enum.UserInputType.MouseButton1,
Enum.UserInputType.MouseButton2,
Enum.UserInputType.MouseButton3,
Enum.UserInputType.MouseMovement,
Enum.UserInputType.MouseWheel,
}
local keyboard = Enum.UserInputType.Keyboard
local function toggleMouse(lastInputType)
if lastInputType == keyboard then
UserInputService.MouseIconEnabled = false
return
end
for _, mouse in pairs(mouseInput) do
if lastInputType == mouse then
UserInputService.MouseIconEnabled = true
return
end
end
end
UserInputService.LastInputTypeChanged:Connect(toggleMouse)

PointerAction

PointerAction fires when the user performs a specific pointer action. In particular, scrolling the mouse wheel.

Parameters

wheel: number
pan: Vector2
pinch: number
gameProcessedEvent: bool

TextBoxFocusReleased

The TextBoxFocusReleased event fires when a client loses focus on a TextBox - typically when a client stops text entry into a TextBox by pressing return or clicking/touching elsewhere on the screen.

For example, the code below prints the name of the TextBox losing focus when the event fires.


local UserInputService = game:GetService("UserInputService")
function TextBoxFocusReleased(textbox)
print(textbox.Name)
end
UserInputService.TextBoxFocusReleased:Connect(TextBoxFocusReleased)

It can be used alongside UserInputService.TextBoxFocused to track when a TextBox gains and loses focus.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

textboxReleased: TextBox

The TextBox that lost focus.


Code Samples

TextBoxFocusReleased

local UserInputService = game:GetService("UserInputService")
UserInputService.TextBoxFocusReleased:Connect(function(textbox)
print("The name of the released focus TextBox is " .. textbox.Name)
end)

TextBoxFocused

The TextBoxFocused event fires when a gains focus on a TextBox - typically when a client clicks/taps on a text box to begin inputting text. This also fires if a text box focus is focused using TextBox:CaptureFocus().

For example, the code below prints the name of the TextBox focused when the event fires.


local UserInputService = game:GetService("UserInputService")
function TextBoxFocused(textbox)
print(textbox.Name)
end)
UserInputService.TextBoxFocused:Connect(TextBoxFocused)

It can be used alongside UserInputService.FocusReleased to track when a text box gains and loses focus.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

textboxFocused: TextBox

The TextBox that gained focus.


Code Samples

Modifying a TextBox on Focused and FocusReleased

local UserInputService = game:GetService("UserInputService")
local function textBoxFocused(textBox)
textBox.BackgroundTransparency = 0
end
local function textBoxFocusReleased(textBox)
textBox.BackgroundTransparency = 0.7
end
UserInputService.TextBoxFocused:Connect(textBoxFocused)
UserInputService.TextBoxFocusReleased:Connect(textBoxFocusReleased)

TouchEnded

The TouchEnded event fires when a user released their finger from the screen of a TouchEnabled device, ending touch input with the device.

This event can be used to determine when a user stops touching the screen of their device. It can be paired with UserInputService.TouchStarted to determine when a user starts and stops touching the screen.

For example, the code below prints the screen position where the user stops touching the screen.


local UserInputService = game:GetService("UserInputService")
function TouchEnded(touch, gameProcessedEvent)
print("Touch ended at " .. tostring(touch.Position))
end
UserInputService.TouchEnded:Connect(TouchEnded)

The touch input object is the same input object throughout the lifetime of the touch. So comparing InputObjects when they are touch objects is valid to determine if it is the same finger.

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

An InputObject instance, which contains information about the user's input.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchLongPress

Fired when a user holds at least one finger for a short amount of time on the same screen position of a TouchEnabled device.

This event can be used to determine when a user holds their finger down on an in-game GuiObject or element.

The example below prints the state of the long press when the user holds at least one finger for a short amount of time on the same screen position. Possible states include: Begin, Change, End, Cancel, and None.


local UserInputService = game:GetService("UserInputService")
function TouchLongPress(TouchPositions, state, gameProcessedEvent)
print("Long press event fired. State of press: " .. tostring(state))
end
UserInputService.TouchLongPress:Connect(TouchLongPress)

To check if a user's device is TouchEnabled, and that touch events will fire, seeUserInputService.TouchEnabled.

It can be paired with UserInputService.TouchStarted and UserInputService.TouchEnded to determine when a user starts and stops touching the screen.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

touchPositions: Array

An array of Vector2 objects, indicating the position of the fingers involved in the gesture.

The Enum.UserInputState of the gesture.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchMoved

The TouchMoved event fires when a user moves their finger on a TouchEnabled device.

This event can be used to determine when a user moves their finger while touching the screen of a TouchEnabled device. It can be useful to track whether a user is moving their finger on the screen, as well as where the user is moving their finger.

The code below prints "Touch moved from" the previous Vector2 position "to " the new Vector2 position of the user's touch on a TouchEnabled device.


local UserInputService = game:GetService("UserInputService")
function onTouchMoved(touch, gameProcessedEvent)
local oldPosition = touch.Position - touch.Delta
print("Touch moved from " .. tostring(oldPosition) .. "to " .. tostring(touch.Position))
end
UserInputService.TouchMoved:Connect(onTouchMoved)

It can be paired with UserInputService.TouchStarted and UserInputService.TouchEnded to determine when a user starts touching the screen, how their finger moves while touching it, and when the they stop touching the screen.

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

An InputObject instance, which contains information about the user's input.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchPan

The TouchPan event fires when a user drags at least one finger on a TouchEnabled device.

This event can be used to determine when a user pans their finger along screen of a TouchEnabled device - such as to rotate the Camera in a custom camera script.

The snippet below prints "Speed of touch drag" followed by the velocity of the user's touch when the user drags their finger on the screen.


local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
print("Speed of touch drag: " .. tostring(velocity))
end)

Take a look at another useful UserInputService function here UserInputService.TouchRotate.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

touchPositions: Array

An array of Vector2 objects, indicating the positions of the touches (e.g. fingers) involved in the gesture.

totalTranslation: Vector2

The size of the pan gesture from start to end (in pixels).

velocity: Vector2

The speed of the pan gesture (in pixels) per second.

The Enum.UserInputState of the gesture.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Create a Custom CameraScript

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end

TouchPinch

Fired when a user places and moves two fingers on the screen of a TouchEnabled device.

For instance, the snippet below prints how much the camera zoom scale has changed since the beginning of the touch pinch.


local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPinch:Connect(function(touchPositions, scale, velocity, state, gameProcessedEvent)
print("Scale difference since beginning of pinch: " .. tostring(scale))
end)

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized. As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

touchPositions: Array

An array of Vector2s, indicating the screen position, in pixels, of the fingers involved in the pinch gesture.

scale: number

The magnitude of the pinch from start to finish (in pixels) divided by the starting pinch positions.

velocity: number

The speed of the pinch gesture (in pixels) per second.

The Enum.UserInputState of the gesture.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Create a Custom CameraScript

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end

TouchRotate

The TouchRotate event fires when a user rotates two fingers on a TouchEnabled device.

For example, the following code prints how much the camera has rotated since the beginning of the touch rotation.


local UserInputService = game:GetService("UserInputService")
UserInputService.TouchRotate:Connect(function(touchPositions, rotation, velocity, state, gameProcessedEvent)
print("Camera has rotated " .. tostring(rotation) .. " degrees!")
end)

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

The core scripts that control the user's camera on a mobile device use code that functions similarly to this event. Best practice for this event is to use it when creating a mobile camera system to override the default core scripts.

See also:

Parameters

touchPositions: Array

An array of Vector2s, indicating the positions of the fingers involved in the gesture.

rotation: number

The number of degree the gesture has rotated since the start of the gesture.

velocity: number

The change in rotation (in degrees) divided by the duration of the change (in seconds).

The Enum.UserInputState of the gesture.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Create a Custom CameraScript

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end

TouchStarted

The TouchStarted event fires when a user places their finger on a TouchEnabled device, beginning touch input with the device.

This event can be used to determine when a user starts touching the screen of their device. It can be paired with UserInputService.TouchEnded to determine when a user starts and stops touching the screen.

The touch input object is the same input object throughout the lifetime of the touch. So comparing InputObjects when they are touch objects is valid to determine if it is the same finger.

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

An InputObject instance, which contains information about the user's input.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Tracking Touches

local UserInputService = game:GetService("UserInputService")
local dragging
local dragInput
local dragStart
local startPos
local gui = script.Parent
local function touchStarted(input, _gameProcessed)
if not dragging then
dragging = true
dragInput = input
dragStart = input.Position
startPos = gui.Position
end
end
local function update(input, _gameProcessed)
if input == dragInput and dragging then
local delta = input.Position - dragStart
gui.Position = UDim2.new(
startPos.X.Scale,
startPos.X.Offset + delta.X,
startPos.Y.Scale,
startPos.Y.Offset + delta.Y
)
end
end
local function touchEnded(input, _gameProcessed)
if input == dragInput then
dragging = false
end
end
UserInputService.TouchStarted:Connect(touchStarted)
UserInputService.TouchMoved:Connect(update)
UserInputService.TouchEnded:Connect(touchEnded)

TouchSwipe

The TouchSwipe event fires when a user swipes their fingers on a TouchEnabled device.

This event can be used to determine when a user swipes their fingers on the screen of their device and the direction that the user swiped.

For more precise tracking of touch input movement, use using UserInputService.TouchMoved

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

See also:

Parameters

swipeDirection: Enum.SwipeDirection

An Enum.SwipeDirection, indicating the direction the user swiped.

numberOfTouches: number

Number of touches (e.g. fingers) involved in the gesture.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

Touch Swipe a GUI

local UserInputService = game:GetService("UserInputService")
local gui = script.Parent
local swipePositionY = gui.Position.Y.Offset
local swipePositionX = gui.Position.X.Offset
local camera = workspace.CurrentCamera
local maxY = camera.ViewportSize.Y - gui.Size.Y.Offset
local maxX = camera.ViewportSize.X - gui.Size.X.Offset
local function TouchSwipe(swipeDirection, _numberOfTouches, _gameProcessedEvent)
if swipeDirection == Enum.SwipeDirection.Up then
swipePositionY = math.max(swipePositionY - 200, 0)
elseif swipeDirection == Enum.SwipeDirection.Down then
swipePositionY = math.min(swipePositionY + 200, maxY)
elseif swipeDirection == Enum.SwipeDirection.Left then
swipePositionX = math.max(swipePositionX - 200, 0)
elseif swipeDirection == Enum.SwipeDirection.Right then
swipePositionX = math.min(swipePositionX + 200, maxX)
end
gui:TweenPosition(UDim2.new(0, swipePositionX, 0, swipePositionY), "Out", "Quad", 0.25, true)
end
UserInputService.TouchSwipe:Connect(TouchSwipe)

TouchTap

The TouchTap event fires when the user touches/taps their finger on the screen on a TouchEnabled device.

This event will fire regardless of whether the user touches/taps the game world or a GuiObject element. If you are looking for an event that only fires when the user touches/taps the game world, use UserInputService.TouchTapInWorld.

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As this event only fires locally, it can only be used in a LocalScript.

Parameters

touchPositions: Array

An array of Vector2 objects, indicating the position of the fingers involved in the tap gesture.

gameProcessedEvent: bool

Indicates whether the game engine internally observed this input and acted on it. Generally this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This is also true for input events connected via ContextActionService.


Code Samples

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchTapInWorld

The TouchTapInWorld event fires when the user touches/taps their finger on the screen on a TouchEnabled device. It is fired when the user taps in the game world.

This event can be used to determine when a user taps the screen and does not tap a GuiObject element. If the user taps a GUI element, UserInputService.TouchTap will fire instead of TouchTapInWorld.

To check if a user's device is TouchEnabled, and that touch events will fire, see UserInputService.TouchEnabled.

This event only fires when the Roblox client window is in focus. For example, inputs will not be captured when the window is minimized.

As it only fires locally, it can only be used in a LocalScript.

See also:

Parameters

position: Vector2

A Vector2 indicating the position of the touch.

processedByUI: bool

Whether the user tapped a GUI element.


Code Samples

Create a Part in World at Touch Position

local UserInputService = game:GetService("UserInputService")
local camera = workspace.CurrentCamera
local LENGTH = 500
local function createPart(position, processedByUI)
-- Do not create a part if the player clicked on a GUI/UI element
if processedByUI then
return
end
-- Get Vector3 world position from the Vector2 viewport position
local unitRay = camera:ViewportPointToRay(position.X, position.Y)
local ray = Ray.new(unitRay.Origin, unitRay.Direction * LENGTH)
local hitPart, worldPosition = workspace:FindPartOnRay(ray)
-- Create a new part at the world position if the player clicked on a part
-- Do not create a new part if player clicks on empty skybox
if hitPart then
local part = Instance.new("Part")
part.Parent = workspace
part.Anchored = true
part.Size = Vector3.new(1, 1, 1)
part.Position = worldPosition
end
end
UserInputService.TouchTapInWorld:Connect(createPart)

WindowFocusReleased

The UserInputService WindowFocusReleased event fires when the window of the Roblox client loses focus - typically when the Roblox client is minimized by the user.

For example, the code below prints "Window focus released" whenever the Roblox client loses focus.


local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocusReleased:Connect(function()
print("Window focus released")
end)

This event can be used alongside UserInputService.WindowFocused to track whether the Roblox client is actively focused on a user's screen.

Since it only fires locally, it can only be used in a LocalScript.


Code Samples

Window Focus AFK Script (Script)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = Instance.new("RemoteEvent")
afkEvent.Name = "AfkEvent"
afkEvent.Parent = ReplicatedStorage
local function setAfk(player, afk)
if afk then
local forcefield = Instance.new("ForceField")
forcefield.Parent = player.Character
else
local forcefield = player.Character:FindFirstChildOfClass("ForceField")
if forcefield then
forcefield:Destroy()
end
end
end
afkEvent.OnServerEvent:Connect(setAfk)
Window Focus AFK Script (LocalScript)

local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = ReplicatedStorage:WaitForChild("AfkEvent")
local function focusGained()
afkEvent:FireServer(false)
end
local function focusReleased()
afkEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)

WindowFocused

The UserInputService WindowFocused event fires when the window of the Roblox client gains focus - typically when the Roblox client is maximized/actively open on the user's screen.

For example, the code below prints "Window focused" whenever the Roblox client gains focus.


local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocused:Connect(function()
print("Window focused")
end)

This event can be used alongside UserInputService.WindowFocusReleased to track whether the Roblox client is actively focused on a user's screen.

As this event only fires locally, it can only be used in a LocalScript.


Code Samples

Window Focus AFK Script (Script)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = Instance.new("RemoteEvent")
afkEvent.Name = "AfkEvent"
afkEvent.Parent = ReplicatedStorage
local function setAfk(player, afk)
if afk then
local forcefield = Instance.new("ForceField")
forcefield.Parent = player.Character
else
local forcefield = player.Character:FindFirstChildOfClass("ForceField")
if forcefield then
forcefield:Destroy()
end
end
end
afkEvent.OnServerEvent:Connect(setAfk)
Window Focus AFK Script (LocalScript)

local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = ReplicatedStorage:WaitForChild("AfkEvent")
local function focusGained()
afkEvent:FireServer(false)
end
local function focusReleased()
afkEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)