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:

Code Samples

UserInputService

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

Summary

Properties

Describes whether the user's device has an accelerometer.

READ ONLY
NOT REPLICATED
HIDDEN
READ ONLY
NOT REPLICATED

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

READ ONLY
NOT REPLICATED
HIDDEN
NOT REPLICATED

Describes whether the user's device has a gyroscope.

READ ONLY
NOT REPLICATED

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

READ ONLY
NOT REPLICATED

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

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

NOT REPLICATED

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

READ ONLY
NOT REPLICATED

Determines whether the Mouse icon is visible.

HIDDEN
READ ONLY
NOT REPLICATED
HIDDEN
READ ONLY
NOT REPLICATED

Determines the position of the on-screen keyboard.

READ ONLY
NOT REPLICATED

Determines the size of the on-screen keyboard.

READ ONLY
NOT REPLICATED

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

READ ONLY
NOT REPLICATED
HIDDEN
READ ONLY
NOT REPLICATED
HIDDEN
READ ONLY
NOT REPLICATED

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

READ ONLY
NOT REPLICATED

Indicates whether the user is using a virtual reality headset.

READ ONLY
NOT REPLICATED

Events


Fired when a user moves a device that has an accelerometer. Used to track real-world device movement within a Roblox game.


Fired when the force of gravity changes on a device that has an enabled accelerometer - such as a mobile device.


Fired when a user rotates a device that has a gyroscope.


Fires when a gamepad is connected to the client. Passes the ''gamepadNum'' of the gamepad that was connected.


Fires when a gamepad is disconnected from the client. Passes the UserInputType of the gamepad that was disconnected.

InputBegan(input: InputObject, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user begins interacting via a Human-Computer Interface device - such as a mouse or gamepad.

InputChanged(input: InputObject, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user changes how they're interacting via a Human-Computer Interface device.

InputEnded(input: InputObject, gameProcessedEvent: boolean): RBXScriptSignal  

Fires when a user stops interacting via a Human-Computer Interface device.


Fires whenever the client makes a request for their character to jump.


Fires when the client's UserInputType is changed.

PointerAction(wheel: number, pan: Vector2, pinch: number, gameProcessedEvent: boolean): RBXScriptSignal  

Fires when the user performs a specific pointer action (wheel, pinch, pan).


Fired when the client loses focus on a TextBox.

TextBoxFocused(textboxFocused: TextBox): RBXScriptSignal  

Fired when the client focuses on a TextBox.

TouchEnded(touch: InputObject, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user releases their finger from the screen on a TouchEnabled device - such as the screen of a mobile device.

TouchLongPress(touchPositions: Array, state: UserInputState, gameProcessedEvent: boolean): RBXScriptSignal  

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

TouchMoved(touch: InputObject, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user moves their finger on a TouchEnabled device - such as the screen of an Apple iPad or iPhone or a Google Android phone.

TouchPan(touchPositions: Array, totalTranslation: Vector2, velocity: Vector2, state: UserInputState, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user drags at least one finger on a TouchEnabled device - such as the screen of an mobile device.

TouchPinch(touchPositions: Array, scale: number, velocity: number, state: UserInputState, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user pinches their fingers on a TouchEnabled device - such as the screen of a mobile device.

TouchRotate(touchPositions: Array, rotation: number, velocity: number, state: UserInputState, gameProcessedEvent: boolean): RBXScriptSignal  

Fires when a user rotates two fingers on a TouchEnabled device - such as the screen of a mobile device.

TouchStarted(touch: InputObject, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user places their finger on a TouchEnabled device - such as the screen of an Apple iPad or iPhone or a Google Android phone.

TouchSwipe(swipeDirection: SwipeDirection, numberOfTouches: number, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user swipes their fingers on a TouchEnabled device - such as the screen of a mobile device.

TouchTap(touchPositions: Array, gameProcessedEvent: boolean): RBXScriptSignal  

Fired when a user taps their finger on a TouchEnabled device - such as the screen of a mobile device.

TouchTapInWorld(position: Vector2, processedByUI: boolean): RBXScriptSignal  

Fires when a user taps the game world on a TouchEnabled device - such as the screen of a mobile device.


Fires when the CFrame of a specified Virtual Reality device changes.


Fires when the window of the Roblox client loses focus on the user's screen.


Fires when the window of the Roblox client gains focus on the user's screen.

Methods

GamepadSupports(gamepadNum: UserInputType, gamepadKeyCode: KeyCode): boolean  

Returns whether the given UserInputType gamepad supports a button corresponding with the given KeyCode.


Returns an array of UserInputType gamepads currently connected.


Returns an InputObject that describes the device's current acceleration.


Returns an InputObject describing the device's current gravity vector.


Returns an InputObject and a CFrame,describing the device's current rotation vector.


Returns the currently TextBox the client is currently focused on.


Returns whether a gamepad with the given UserInputType''gamepadNum'' is connected.


Returns an array of InputObjects for all available inputs on the given gamepad, representing each input's last input state.


Returns an array of InputObjects associated with the keys currently being pressed down.


Returns the UserInputType associated with the user's most recent input.


Returns an array of InputObjects corresponding with the mouse buttons currently being held down.


Returns the change, in pixels, of the position of the player's Mouse in the last rendered frame. Only works if the mouse is locked.


Returns the current screen location of the player's Mouse relative to the top left corner of the screen.


Returns an array of gamepads connected and enabled for GUI navigation in descending order of priority.


Returns a string representing a key the user should press in order to input a given KeyCode.


Returns an array of KeyCodes that the gamepad associated with the given UserInputType supports.


Returns a CFrame describing the position and orientation of a specified virtual reality device.

IsGamepadButtonDown(gamepadNum: UserInputType, gamepadKeyCode: KeyCode): boolean  

Determines whether a particular button is pressed on a particular gamepad.

IsKeyDown(keyCode: KeyCode): boolean  

Returns whether the given key is currently held down.


Returns whether the given mouse button is currently held down.


Returns true if the specified UserInputType.Gamepad is allowed to control the navigation GUIs.


Recenters the CFrame of the VR headset to the current orientation of the headset worn by the user.

SendAppUISizes(statusBarSize: Vector2, navBarSize: Vector2, bottomBarSize: Vector2, rightBarSize: Vector2): void  


SetNavigationGamepad(gamepadEnum: UserInputType, enabled: boolean): void  

Sets whether or not the specified Gamepad can move the GUI navigator.

Properties

AccelerometerEnabled

Read Only
Not Replicated

This property describes whether the 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.


1local userInputService = game:GetService("UserInputService")
2
3local accelerometerEnabled = oserInputService.AccelerometerEnabled
4if accelerometerEnabled then
5 print("Accelerometer enabled!")
6else
7 print("Accelerometer not enabled!")
8end
9

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.

BottomBarSize

Hidden
Read Only
Not Replicated

GamepadEnabled

Read Only
Not Replicated

This property describes whether the device being used by a user has an available gamepad.


1local userInputService = game:GetService("UserInputService")
2
3if userInputService.GamepadEnabled then
4 print("Gamepad enabled")
5else
6 print("Gamepad not enabled")
7end
8

If gamepads are available, you can use UserInputService:GetConnectedGamepads() to retrieve a list of connected gamepads and UserInputService:GetNavigationGamepads() to retrieve a list of connected gamepads that also controlnavigation GUIs.

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

See also:

GazeSelectionEnabled

Hidden
Not Replicated

GyroscopeEnabled

Read Only
Not Replicated

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

A gyroscope is an 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.


1local UserInputService = game:GetService("UserInputService")
2
3local gyroIsEnabled = UserInputService.GyroscopeEnabled
4if (gyroIsEnabled) then
5 print("Gyroscope is enabled!")
6else
7 print("Gyroscope is not enabled!")
8end
9

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

KeyboardEnabled

Read Only
Not Replicated

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.

LegacyInputEventsEnabled

MouseBehavior

This property sets how the user's mouse behaves based on the 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.

MouseDeltaSensitivity

Not Replicated

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).

MouseEnabled

Read Only
Not Replicated

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.


1local UserInputService = game:GetService("UserInputService")
2
3if (UserInputService.MouseEnabled) then
4 print("The user's device has an available mouse!")
5else
6 print("The user's device does not have an available mouse!")
7end
8

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:

MouseIconEnabled

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.


1local userInputService = game:GetService("UserInputService")
2
3userInputService.MouseIconEnabled = false
4

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

Hidden
Read Only
Not Replicated

OnScreenKeyboardAnimationDuration

Hidden
Read Only
Not Replicated

OnScreenKeyboardPosition

Read Only
Not Replicated

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.

The code snippet below prints the position of the keyboard.


1local userInputService = game:GetService("UserInputService")
2print(userInputService.OnScreenKeyboardPosition)
3

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

On screen keyboard

See also:

OnScreenKeyboardSize

Read Only
Not Replicated

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.

The code snippet below prints the size of the keyboard.


1local userInputService = game:GetService("UserInputService")
2print(userInputService.OnScreenKeyboardSize)
3

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

On screen keyboard

See also:

OnScreenKeyboardVisible

Read Only
Not Replicated

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

The code snippet below prints whether the keyboard is visible.


1local userInputService = game:GetService("UserInputService")
2
3local keyboardIsVisible = userInputService.OnScreenKeyboardIsVisible
4if (keyboardIsVisible) then
5 print("On-screen keyboard is visible!")
6else
7 print("On-screen keyboard is not visible!")
8end
9

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

On screen keyboard

See also:

OverrideMouseIconBehavior

RightBarSize

Hidden
Read Only
Not Replicated

StatusBarSize

Hidden
Read Only
Not Replicated

TouchEnabled

Read Only
Not Replicated

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.


1local userInputService = game:GetService("UserInputService")
2
3if userInputService.TouchEnabled then
4 print("The user's device has a touchscreen!")
5else
6 print("The user's device does not have a touchscreen!")
7end
8

See also:

VREnabled

Read Only
Not Replicated

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.


1local userInputService = game:GetService("UserInputService")
2
3local isUsingVR = userInputService.VREnabled
4if (isUsingVR) then
5 print("User is using a VR headset!")
6else
7 print("User is not using a VR headset!")
8end
9

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

See also:

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

1local UserInputService = game:GetService("UserInputService")
2local Players = game:GetService("Players")
3
4local SENSITIVITY = 0.2
5
6local player = Players.LocalPlayer
7local character = player.Character or player.CharacterAdded:Wait()
8local humanoid = character:WaitForChild("Humanoid")
9
10local ready = true
11
12local function changeAcceleration(acceleration)
13 if ready then
14 ready = false
15 local accel = acceleration.Position
16
17 if accel.Y >= SENSITIVITY then
18 humanoid.Jump = true
19 end
20
21 if accel.Z <= -SENSITIVITY then
22 humanoid:Move(Vector3.new(-1, 0, 0))
23 end
24 if accel.Z >= SENSITIVITY then
25 humanoid:Move(Vector3.new(1, 0, 0))
26 end
27 if accel.X <= -SENSITIVITY then
28 humanoid:Move(Vector3.new(0, 0, 1))
29 end
30 if accel.X >= SENSITIVITY then
31 humanoid:Move(Vector3.new(0, 0, -1))
32 end
33 task.wait(1)
34 ready = true
35 end
36end
37
38UserInputService.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

1local UserInputService = game:GetService("UserInputService")
2
3local Ball = workspace.Ball
4
5local RealGravity = Instance.new("BodyForce")
6RealGravity.Parent = Ball
7
8local AntiGravity = Instance.new("BodyForce")
9AntiGravity.Parent = Ball
10AntiGravity.force = Vector3.new(0, workspace.Gravity * Ball:GetMass(), 0)
11
12local function MoveBall(gravity)
13 RealGravity.force = gravity.Position * workspace.Gravity * workspace.Ball:GetMass()
14end
15
16if UserInputService.AccelerometerEnabled then
17 UserInputService.DeviceGravityChanged:Connect(MoveBall)
18end
Create a Gyroscopic Camera

1local UserInputService = game:GetService("UserInputService")
2local RunService = game:GetService("RunService")
3local Players = game:GetService("Players")
4
5local player = Players.LocalPlayer
6local character = player.CharacterAdded:Wait()
7local head = character:WaitForChild("Head")
8
9local camera = workspace.CurrentCamera
10local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
11local lastInputFrame = nil
12local upsideDown = false
13
14task.wait()
15
16local orientationSet = false
17local function GravityChanged(gravity)
18 if not orientationSet then
19 upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
20
21 orientationSet = true
22 end
23end
24
25local function RotationChanged(_rotation, rotCFrame)
26 if orientationSet then
27 if not lastInputFrame then
28 lastInputFrame = rotCFrame
29 end
30
31 local delta = rotCFrame * lastInputFrame:inverse()
32 local x, y, z = delta:ToEulerAnglesXYZ()
33 if upsideDown then
34 delta = CFrame.Angles(-x, y, z)
35 else
36 delta = CFrame.Angles(x, -y, z)
37 end
38 currentRotation = currentRotation * delta
39
40 lastInputFrame = rotCFrame
41 end
42end
43
44local function HideCharacter()
45 for _, limb in pairs(character:GetChildren()) do
46 if limb:IsA("Part") then
47 limb.Transparency = 1
48 end
49 end
50end
51
52if UserInputService.GyroscopeEnabled then
53 UserInputService.DeviceGravityChanged:Connect(GravityChanged)
54 UserInputService.DeviceRotationChanged:Connect(RotationChanged)
55
56 HideCharacter()
57
58 RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
59 camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
60 camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
61 end)
62end

DeviceRotationChanged

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

A gyroscope is an 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

Move a Ball using the Accelerometer

1local UserInputService = game:GetService("UserInputService")
2
3local Ball = workspace.Ball
4
5local RealGravity = Instance.new("BodyForce")
6RealGravity.Parent = Ball
7
8local AntiGravity = Instance.new("BodyForce")
9AntiGravity.Parent = Ball
10AntiGravity.force = Vector3.new(0, workspace.Gravity * Ball:GetMass(), 0)
11
12local function MoveBall(gravity)
13 RealGravity.force = gravity.Position * workspace.Gravity * workspace.Ball:GetMass()
14end
15
16if UserInputService.AccelerometerEnabled then
17 UserInputService.DeviceGravityChanged:Connect(MoveBall)
18end
Create a Gyroscopic Camera

1local UserInputService = game:GetService("UserInputService")
2local RunService = game:GetService("RunService")
3local Players = game:GetService("Players")
4
5local player = Players.LocalPlayer
6local character = player.CharacterAdded:Wait()
7local head = character:WaitForChild("Head")
8
9local camera = workspace.CurrentCamera
10local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
11local lastInputFrame = nil
12local upsideDown = false
13
14task.wait()
15
16local orientationSet = false
17local function GravityChanged(gravity)
18 if not orientationSet then
19 upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
20
21 orientationSet = true
22 end
23end
24
25local function RotationChanged(_rotation, rotCFrame)
26 if orientationSet then
27 if not lastInputFrame then
28 lastInputFrame = rotCFrame
29 end
30
31 local delta = rotCFrame * lastInputFrame:inverse()
32 local x, y, z = delta:ToEulerAnglesXYZ()
33 if upsideDown then
34 delta = CFrame.Angles(-x, y, z)
35 else
36 delta = CFrame.Angles(x, -y, z)
37 end
38 currentRotation = currentRotation * delta
39
40 lastInputFrame = rotCFrame
41 end
42end
43
44local function HideCharacter()
45 for _, limb in pairs(character:GetChildren()) do
46 if limb:IsA("Part") then
47 limb.Transparency = 1
48 end
49 end
50end
51
52if UserInputService.GyroscopeEnabled then
53 UserInputService.DeviceGravityChanged:Connect(GravityChanged)
54 UserInputService.DeviceRotationChanged:Connect(RotationChanged)
55
56 HideCharacter()
57
58 RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
59 camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
60 camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
61 end)
62end

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:GetNavigationGamepads() and 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.


1local userInputService = game:GetService("UserInputService")
2
3local function GamepadConnected(gamepad)
4 print("Player has plugged controller: " .. tostring(gamepad))
5end)
6
7userInputService.GamepadConnected:Connect(GamepadConnected)
8

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: UserInputType

The UserInputType of the connected gamepad.


Code Samples

How to Use the Right Gamepad for Input

1local UserInputService = game:GetService("UserInputService")
2
3function GetActiveGamepad()
4 local activateGamepad = nil
5 local navigationGamepads = {}
6
7 navigationGamepads = UserInputService:GetNavigationGamepads()
8
9 if #navigationGamepads > 1 then
10 for _index, gamepad in ipairs(navigationGamepads) do
11 if activateGamepad == nil or gamepad.Value < activateGamepad.Value then
12 activateGamepad = gamepad
13 end
14 end
15 else
16 local connectedGamepads = {}
17
18 connectedGamepads = UserInputService:GetConnectedGamepads()
19
20 if #connectedGamepads > 0 then
21 for _index, gamepad in ipairs(connectedGamepads) do
22 if activateGamepad == nil or gamepad.Value < activateGamepad.Value then
23 activateGamepad = gamepad
24 end
25 end
26 end
27 if activateGamepad == nil then -- nothing is connected, at least set up for gamepad1
28 activateGamepad = Enum.UserInputType.Gamepad1
29 end
30 end
31
32 return activateGamepad
33end
34
35if UserInputService.GamepadEnabled then
36 print(GetActiveGamepad())
37end

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:GetNavigationGamepads() and 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.


1local userInputService = game:GetService("UserInputService")
2
3local function GamepadDisconnected(gamepad)
4 print("Player has unplugged controller: " .. tostring(gamepad))
5end)
6
7userInputService.GamepadDisconnected:Connect(GamepadDisconnected)
8

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

See also:

Parameters

gamepadNum: UserInputType

TheUserInputType of the disconnected gamepad.


Code Samples

How to Use the Right Gamepad for Input

1local UserInputService = game:GetService("UserInputService")
2
3function GetActiveGamepad()
4 local activateGamepad = nil
5 local navigationGamepads = {}
6
7 navigationGamepads = UserInputService:GetNavigationGamepads()
8
9 if #navigationGamepads > 1 then
10 for _index, gamepad in ipairs(navigationGamepads) do
11 if activateGamepad == nil or gamepad.Value < activateGamepad.Value then
12 activateGamepad = gamepad
13 end
14 end
15 else
16 local connectedGamepads = {}
17
18 connectedGamepads = UserInputService:GetConnectedGamepads()
19
20 if #connectedGamepads > 0 then
21 for _index, gamepad in ipairs(connectedGamepads) do
22 if activateGamepad == nil or gamepad.Value < activateGamepad.Value then
23 activateGamepad = gamepad
24 end
25 end
26 end
27 if activateGamepad == nil then -- nothing is connected, at least set up for gamepad1
28 activateGamepad = Enum.UserInputType.Gamepad1
29 end
30 end
31
32 return activateGamepad
33end
34
35if UserInputService.GamepadEnabled then
36 print(GetActiveGamepad())
37end

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: boolean

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

1-- In order to use the InputBegan event, the UserInputService service must be used
2local UserInputService = game:GetService("UserInputService")
3
4-- A sample function providing multiple usage cases for various types of user input
5UserInputService.InputBegan:Connect(function(input, gameProcessed)
6 if input.UserInputType == Enum.UserInputType.Keyboard then
7 print("A key is being pushed down! Key:", input.KeyCode)
8 elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
9 print("The left mouse button has been pressed down at", input.Position)
10 elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
11 print("The right mouse button has been pressed down at", input.Position)
12 elseif input.UserInputType == Enum.UserInputType.Touch then
13 print("A touchscreen input has started at", input.Position)
14 elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
15 print("A button is being pressed on a gamepad! Button:", input.KeyCode)
16 end
17
18 if gameProcessed then
19 print("The game engine internally observed this input!")
20 else
21 print("The game engine did not internally observe this input!")
22 end
23end)

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: boolean

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

1-- In order to use the InputChanged event, the UserInputService service must be used
2local UserInputService = game:GetService("UserInputService")
3
4-- Prints the current input position and the change (delta) in position
5local function printMovement(input)
6 print("Position:", input.Position)
7 print("Movement Delta:", input.Delta)
8end
9
10-- A sample function providing multiple usage cases for various types of user input
11local function InputChanged(input, _gameProcessed)
12 if input.UserInputType == Enum.UserInputType.MouseMovement then
13 print("The mouse has been moved!")
14 printMovement(input)
15 elseif input.UserInputType == Enum.UserInputType.MouseWheel then
16 print("The mouse wheel has been scrolled!")
17 print("Wheel Movement:", input.Position.Z)
18 elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
19 if input.KeyCode == Enum.KeyCode.Thumbstick1 then
20 print("The left thumbstick has been moved!")
21 printMovement(input)
22 elseif input.KeyCode == Enum.KeyCode.Thumbstick2 then
23 print("The right thumbstick has been moved!")
24 printMovement(input)
25 elseif input.KeyCode == Enum.KeyCode.ButtonL2 then
26 print("The pressure being applied to the left trigger has changed!")
27 print("Pressure:", input.Position.Z)
28 elseif input.KeyCode == Enum.KeyCode.ButtonR2 then
29 print("The pressure being applied to the right trigger has changed!")
30 print("Pressure:", input.Position.Z)
31 end
32 elseif input.UserInputType == Enum.UserInputType.Touch then
33 print("The user's finger is moving on the screen!")
34 printMovement(input)
35 elseif input.UserInputType == Enum.UserInputType.Gyro then
36 local _rotInput, rotCFrame = UserInputService:GetDeviceRotation()
37 local rotX, rotY, rotZ = rotCFrame:toEulerAnglesXYZ()
38 local rot = Vector3.new(math.deg(rotX), math.deg(rotY), math.deg(rotZ))
39 print("The rotation of the user's mobile device has been changed!")
40 print("Position", rotCFrame.p)
41 print("Rotation:", rot)
42 elseif input.UserInputType == Enum.UserInputType.Accelerometer then
43 print("The acceleration of the user's mobile device has been changed!")
44 printMovement(input)
45 end
46end
47
48UserInputService.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: boolean

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

1-- In order to use the InputChanged event, the UserInputService service must be used
2local UserInputService = game:GetService("UserInputService")
3
4-- A sample function providing multiple usage cases for various types of user input
5UserInputService.InputEnded:Connect(function(input, gameProcessed)
6 if input.UserInputType == Enum.UserInputType.Keyboard then
7 print("A key has been released! Key:", input.KeyCode)
8 elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
9 print("The left mouse button has been released at", input.Position)
10 elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
11 print("The right mouse button has been released at", input.Position)
12 elseif input.UserInputType == Enum.UserInputType.Touch then
13 print("A touchscreen input has been released at", input.Position)
14 elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
15 print("A button has been released on a gamepad! Button:", input.KeyCode)
16 end
17
18 if gameProcessed then
19 print("The game engine internally observed this input!")
20 else
21 print("The game engine did not internally observe this input!")
22 end
23end)

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.


1local UserInputService = game:GetService("UserInputService")
2
3function onJumpRequest()
4 print("Jump!")
5end
6
7UserInputService.JumpRequest:Connect(onJumpRequest)
8

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

1local UserInputService = game:GetService("UserInputService")
2local Players = game:GetService("Players")
3
4local player = Players.LocalPlayer
5local character = player.Character or player.CharacterAdded:Wait()
6local humanoid = character:WaitForChild("Humanoid")
7
8-- Fires when the user tries to jump
9local function jump()
10 humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
11end
12
13UserInputService.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: UserInputType

A UserInputType indicating the last input type.


Code Samples

Hide Mouse During Keyboard Input

1local UserInputService = game:GetService("UserInputService")
2
3local mouseInput = {
4 Enum.UserInputType.MouseButton1,
5 Enum.UserInputType.MouseButton2,
6 Enum.UserInputType.MouseButton3,
7 Enum.UserInputType.MouseMovement,
8 Enum.UserInputType.MouseWheel,
9}
10
11local keyboard = Enum.UserInputType.Keyboard
12
13local function toggleMouse(lastInputType)
14 if lastInputType == keyboard then
15 UserInputService.MouseIconEnabled = false
16 return
17 end
18
19 for _, mouse in pairs(mouseInput) do
20 if lastInputType == mouse then
21 UserInputService.MouseIconEnabled = true
22 return
23 end
24 end
25end
26
27UserInputService.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: boolean

StatusBarTapped

Roblox Script Security

Parameters

position: Vector2

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 the name of the TextBox losing focus when the event fires.


1local UserInputService = game:GetService("UserInputService")
2
3function TextBoxFocusReleased(textbox)
4 print(textbox.Name)
5end
6
7UserInputService.TextBoxFocusReleased:Connect(TextBoxFocusReleased)
8

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

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

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 the name of the TextBox focused when the event fires.


1local UserInputService = game:GetService("UserInputService")
2
3function TextBoxFocused(textbox)
4 print(textbox.Name)
5end)
6
7UserInputService.TextBoxFocused:Connect(TextBoxFocused)
8

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

1local UserInputService = game:GetService("UserInputService")
2
3local function textBoxFocused(textBox)
4 textBox.BackgroundTransparency = 0
5end
6
7local function textBoxFocusReleased(textBox)
8 textBox.BackgroundTransparency = 0.7
9end
10
11UserInputService.TextBoxFocused:Connect(textBoxFocused)
12UserInputService.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.


1local UserInputService = game:GetService("UserInputService")
2
3function TouchEnded(touch, gameProcessedEvent)
4 print("Touch ended at "..tostring(touch.Position))
5end
6
7UserInputService.TouchEnded:Connect(TouchEnded)
8

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: boolean

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

1local UserInputService = game:GetService("UserInputService")
2
3-- The parent of this script (a ScreenGui)
4local touchScreenGui = script.Parent
5
6-- Create the GUI frame that the user interacts with through Touch
7-- events
8local touchGui = Instance.new("Frame")
9touchGui.Name = "TouchGui"
10touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
11
12-- Fires when the touches their device's screen
13local function TouchTap(touchPositions, _gameProcessedEvent)
14 touchGui.Parent = touchScreenGui
15 touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
16 touchGui.Size = UDim2.new(0, 50, 0, 50)
17end
18
19-- Fires when a user starts touching their device's screen and does not
20-- move their finger for a short period of time
21local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
22 touchGui.Size = UDim2.new(0, 100, 0, 100)
23end
24
25-- Fires when the user moves their finger while touching their device's
26-- screen
27local function TouchMove(touch, _gameProcessedEvent)
28 touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
29end
30
31-- Fires when the user stops touching their device's screen
32local function TouchEnd(_touch, _gameProcessedEvent)
33 touchGui.Parent = nil
34 touchGui.Size = UDim2.new(0, 50, 0, 50)
35end
36
37-- Only use the Touch events if the user is on a mobile device
38if UserInputService.TouchEnabled then
39 UserInputService.TouchTap:Connect(TouchTap)
40 UserInputService.TouchLongPress:Connect(TouchLong)
41 UserInputService.TouchMoved:Connect(TouchMove)
42 UserInputService.TouchEnded:Connect(TouchEnd)
43end

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 GUI or element.

The example below prints the state of the long press when the user 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.


1local userInputService = game:GetService("UserInputService")
2
3function TouchLongPress(TouchPositions, state, gameProcessedEvent)
4 print("Long press event fired. State of press: "..tostring(state))
5end
6
7userInputService.TouchLongPress:Connect(TouchLongPress)
8

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 Vector2s, indicating the position of the fingers involved in the gesture.

The UserInputState of the gesture.

gameProcessedEvent: boolean

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

1local UserInputService = game:GetService("UserInputService")
2
3-- The parent of this script (a ScreenGui)
4local touchScreenGui = script.Parent
5
6-- Create the GUI frame that the user interacts with through Touch
7-- events
8local touchGui = Instance.new("Frame")
9touchGui.Name = "TouchGui"
10touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
11
12-- Fires when the touches their device's screen
13local function TouchTap(touchPositions, _gameProcessedEvent)
14 touchGui.Parent = touchScreenGui
15 touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
16 touchGui.Size = UDim2.new(0, 50, 0, 50)
17end
18
19-- Fires when a user starts touching their device's screen and does not
20-- move their finger for a short period of time
21local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
22 touchGui.Size = UDim2.new(0, 100, 0, 100)
23end
24
25-- Fires when the user moves their finger while touching their device's
26-- screen
27local function TouchMove(touch, _gameProcessedEvent)
28 touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
29end
30
31-- Fires when the user stops touching their device's screen
32local function TouchEnd(_touch, _gameProcessedEvent)
33 touchGui.Parent = nil
34 touchGui.Size = UDim2.new(0, 50, 0, 50)
35end
36
37-- Only use the Touch events if the user is on a mobile device
38if UserInputService.TouchEnabled then
39 UserInputService.TouchTap:Connect(TouchTap)
40 UserInputService.TouchLongPress:Connect(TouchLong)
41 UserInputService.TouchMoved:Connect(TouchMove)
42 UserInputService.TouchEnded:Connect(TouchEnd)
43end

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.


1local UserInputService = game:GetService("UserInputService")
2
3function onTouchMoved(touch, gameProcessedEvent)
4 local oldPosition = touch.Position - touch.Delta
5 print("Touch moved from " .. tostring(oldPosition) .. "to " .. tostring(touch.Position))
6end
7
8UserInputService.TouchMoved:Connect(onTouchMoved)
9

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: boolean

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

1local UserInputService = game:GetService("UserInputService")
2
3-- The parent of this script (a ScreenGui)
4local touchScreenGui = script.Parent
5
6-- Create the GUI frame that the user interacts with through Touch
7-- events
8local touchGui = Instance.new("Frame")
9touchGui.Name = "TouchGui"
10touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
11
12-- Fires when the touches their device's screen
13local function TouchTap(touchPositions, _gameProcessedEvent)
14 touchGui.Parent = touchScreenGui
15 touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
16 touchGui.Size = UDim2.new(0, 50, 0, 50)
17end
18
19-- Fires when a user starts touching their device's screen and does not
20-- move their finger for a short period of time
21local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
22 touchGui.Size = UDim2.new(0, 100, 0, 100)
23end
24
25-- Fires when the user moves their finger while touching their device's
26-- screen
27local function TouchMove(touch, _gameProcessedEvent)
28 touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
29end
30
31-- Fires when the user stops touching their device's screen
32local function TouchEnd(_touch, _gameProcessedEvent)
33 touchGui.Parent = nil
34 touchGui.Size = UDim2.new(0, 50, 0, 50)
35end
36
37-- Only use the Touch events if the user is on a mobile device
38if UserInputService.TouchEnabled then
39 UserInputService.TouchTap:Connect(TouchTap)
40 UserInputService.TouchLongPress:Connect(TouchLong)
41 UserInputService.TouchMoved:Connect(TouchMove)
42 UserInputService.TouchEnded:Connect(TouchEnd)
43end

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.


1local userInputService = game:GetService("UserInputService")
2
3userInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
4 print("Speed of touch drag: "..tostring(velocity))
5end)
6

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 Vector2s, 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 UserInputState of the gesture.

gameProcessedEvent: boolean

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

1local UserInputService = game:GetService("UserInputService")
2local RunService = game:GetService("RunService")
3local Players = game:GetService("Players")
4
5local camera = workspace.CurrentCamera
6
7local player = Players.LocalPlayer
8local character = player.CharacterAdded:Wait()
9local torso = character:WaitForChild("HumanoidRootPart")
10local playerPosition = torso.Position
11
12local default_CameraPosition = torso.Position
13local default_CameraRotation = Vector2.new(0, math.rad(-60))
14local default_CameraZoom = 15
15
16local cameraPosition = default_CameraPosition
17local cameraRotation = default_CameraRotation
18local cameraZoom = default_CameraZoom
19
20local cameraZoomBounds = nil -- {10,200}
21local cameraRotateSpeed = 10
22local cameraMouseRotateSpeed = 0.25
23local cameraTouchRotateSpeed = 10
24
25local function SetCameraMode()
26 camera.CameraType = "Scriptable"
27 camera.FieldOfView = 80
28 camera.CameraSubject = nil
29end
30
31local function UpdateCamera()
32 SetCameraMode()
33 local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
34 camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
35 camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
36end
37
38local lastTouchTranslation = nil
39local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
40 if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
41 local difference = totalTranslation - lastTouchTranslation
42 cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
43 UpdateCamera()
44 end
45 lastTouchTranslation = totalTranslation
46end
47
48local lastTouchRotation = nil
49local function TouchRotate(_touchPositions, rotation, _velocity, state)
50 if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
51 local difference = rotation - lastTouchRotation
52 cameraRotation = cameraRotation
53 + Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
54 UpdateCamera()
55 end
56 lastTouchRotation = rotation
57end
58
59local lastTouchScale = nil
60local function TouchZoom(_touchPositions, scale, _velocity, state)
61 if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
62 local difference = scale - lastTouchScale
63 cameraZoom = cameraZoom * (1 + difference)
64 if cameraZoomBounds ~= nil then
65 cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
66 else
67 cameraZoom = math.max(cameraZoom, 0)
68 end
69 UpdateCamera()
70 end
71 lastTouchScale = scale
72end
73
74local function Input(inputObject)
75 if inputObject.UserInputType == Enum.UserInputType.Keyboard then
76 if inputObject.UserInputState == Enum.UserInputState.Begin then
77 -- (I) Zoom In
78 if inputObject.KeyCode == Enum.KeyCode.I then
79 cameraZoom = cameraZoom - 15
80 elseif inputObject.KeyCode == Enum.KeyCode.O then
81 cameraZoom = cameraZoom + 15
82 end
83
84 -- (O) Zoom Out
85 if cameraZoomBounds ~= nil then
86 cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
87 else
88 cameraZoom = math.max(cameraZoom, 0)
89 end
90
91 UpdateCamera()
92 end
93 end
94
95 local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
96 if pressed then
97 UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
98 local rotation = UserInputService:GetMouseDelta()
99 cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
100 else
101 UserInputService.MouseBehavior = Enum.MouseBehavior.Default
102 end
103end
104
105local function PlayerChanged()
106 local movement = torso.Position - playerPosition
107 cameraPosition = cameraPosition + movement
108 playerPosition = torso.Position
109
110 UpdateCamera()
111end
112
113-- Determine whether the user is on a mobile device
114if UserInputService.TouchEnabled then
115 -- The user is on a mobile device, use Touch events
116 UserInputService.TouchPan:Connect(TouchMove)
117 UserInputService.TouchRotate:Connect(TouchRotate)
118 UserInputService.TouchPinch:Connect(TouchZoom)
119else
120 -- The user is not on a mobile device use Input events
121 UserInputService.InputBegan:Connect(Input)
122 UserInputService.InputChanged:Connect(Input)
123 UserInputService.InputEnded:Connect(Input)
124
125 -- Camera controlled by player movement
126 task.wait(2)
127 RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
128end

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,


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

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.

Core scripts use similar logic to zoom the user's camera when a user pinches their fingers on a mobile device. Best practice for this event is to use it when creating a mobile camera system to override the default core script.

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 UserInputState of the gesture.

gameProcessedEvent: boolean

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

1local UserInputService = game:GetService("UserInputService")
2local RunService = game:GetService("RunService")
3local Players = game:GetService("Players")
4
5local camera = workspace.CurrentCamera
6
7local player = Players.LocalPlayer
8local character = player.CharacterAdded:Wait()
9local torso = character:WaitForChild("HumanoidRootPart")
10local playerPosition = torso.Position
11
12local default_CameraPosition = torso.Position
13local default_CameraRotation = Vector2.new(0, math.rad(-60))
14local default_CameraZoom = 15
15
16local cameraPosition = default_CameraPosition
17local cameraRotation = default_CameraRotation
18local cameraZoom = default_CameraZoom
19
20local cameraZoomBounds = nil -- {10,200}
21local cameraRotateSpeed = 10
22local cameraMouseRotateSpeed = 0.25
23local cameraTouchRotateSpeed = 10
24
25local function SetCameraMode()
26 camera.CameraType = "Scriptable"
27 camera.FieldOfView = 80
28 camera.CameraSubject = nil
29end
30
31local function UpdateCamera()
32 SetCameraMode()
33