UserInputService
UserInputService is primarily used to detect the input types available on a user's device, as well as detect input events. It allows you to perform different actions depending on the device and, in turn, provide the best experience for the end user.
As this service is intended for client-side usage only, its properties, methods, and events can only be used in a LocalScript, a ModuleScript required by a LocalScript, or a Script with RunContext set to Enum.RunContext.Client.
Summary
Properties
Describes whether the user's device has an accelerometer.
Describes whether the user's device has an available gamepad.
Describes whether the user's device has a gyroscope.
Describes whether the user's device has a keyboard available.
Determines whether the user's mouse can be moved freely or is locked.
Scales the delta (change) output of the user's Mouse.
Describes whether the user's device has a mouse available.
The content ID of the image for the user's mouse icon.
Determines whether the mouse icon is visible.
Determines the position of the on-screen keyboard.
Determines the size of the on-screen keyboard.
Describes whether an on-screen keyboard is currently visible on the user's screen.
Queries the primary input type a player is using, based on anticipated user behavior.
Describes whether the user's device has a touch screen available.
Indicates whether the user is using a virtual reality headset.
Methods
Returns whether the given Enum.UserInputType gamepad supports a button corresponding with the given Enum.KeyCode.
Returns an array of Enum.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 Enum.UserInputType is connected.
Returns an array of InputObjects for all available inputs on the given gamepad, representing each input's last input state.
Returns an image for the requested Enum.KeyCode.
Returns an array of InputObjects associated with the keys currently being pressed down.
Returns the Enum.UserInputType associated with the user's most recent input.
Returns an array of InputObjects associated 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 GuiObject navigation in descending order of priority.
Returns a string representing a key the user should press in order to input a given Enum.KeyCode.
Returns an array of KeyCodes that the gamepad associated with the given Enum.UserInputType supports.
Determines whether a particular button is pressed on a gamepad.
Returns whether the given key is currently held down.
Returns whether the given mouse button is currently held down.
Returns true if the specified gamepad is allowed to control navigation and selection GuiObjects.
Recenters the CFrame of the VR headset to the current orientation of the headset worn by the user.
Sets whether or not the specified gamepad can move the GuiObject navigator.
Events
Fires when a user moves a device that has an accelerometer.
Fires when the force of gravity changes on a device that has an enabled accelerometer.
Fires when a user rotates a device that has a gyroscope.
Fires when a gamepad is connected to the client.
Fires when a gamepad is disconnected from the client.
Fires when a user begins interacting with an input device such as a mouse or gamepad.
Fires when a user changes how they're interacting with an input device such as a mouse or gamepad.
Fires when a user stops interacting with an input device such as a mouse or gamepad.
Fires whenever the client makes a request for their character to jump.
Fires whenever the client's Enum.UserInputType is changed.
- PointerAction(wheel : number,pan : Vector2,pinch : number,gameProcessedEvent : boolean):RBXScriptSignal
Fires when the user performs a specific pointer action.
Fires when the client loses focus on a TextBox.
Fires when the client focuses on a TextBox.
- TouchDrag(dragDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Fires when the user drags on the screen of a TouchEnabled device.
Fires when a user releases their finger from the screen of a TouchEnabled device.
- TouchLongPress(touchPositions : Array,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Fires when a user holds at least one finger for a short amount of time on the screen of a TouchEnabled device.
Fires when a user moves their finger on the screen of a TouchEnabled device.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Fires when the user drags at least one finger on the screen of a TouchEnabled device.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Fires when a user performs a pinch gesture on the screen of a TouchEnabled device.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Fires when a user rotates two fingers on the screen of a TouchEnabled device.
Fires when a user places their finger on the screen of a TouchEnabled device.
- TouchSwipe(swipeDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Fires on a TouchEnabled device when a user places their finger(s) down on the screen, pans across the screen, and lifts their finger(s) off with a certain speed of movement.
Fires when a user taps their finger on the screen of a TouchEnabled device.
Fires when a user taps their finger on the screen of a TouchEnabled device and the tap location is in the 3D world.
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.
Properties
AccelerometerEnabled
Code Samples
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
GamepadEnabled
GyroscopeEnabled
KeyboardEnabled
MouseBehavior
MouseDeltaSensitivity
MouseEnabled
MouseIcon
Code Samples
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()
MouseIconEnabled
OnScreenKeyboardPosition
OnScreenKeyboardSize
OnScreenKeyboardVisible
PreferredInput
Code Samples
local UserInputService = game:GetService("UserInputService")
local function preferredInputChanged()
local preferredInput = UserInputService.PreferredInput
if preferredInput == Enum.PreferredInput.Touch then
-- Player is on touch-enabled device with no other input types available/connected
print("Touch")
elseif preferredInput == Enum.PreferredInput.Gamepad then
-- Player has connected or most recently interacted with a gamepad
print("Gamepad")
elseif preferredInput == Enum.PreferredInput.KeyboardAndMouse then
-- Player has connected or most recently interacted with a keyboard or mouse
print("KeyboardAndMouse")
end
end
preferredInputChanged()
UserInputService:GetPropertyChangedSignal("PreferredInput"):Connect(function()
preferredInputChanged()
end)
TouchEnabled
VREnabled
Methods
GamepadSupports
Parameters
Returns
GetDeviceAcceleration
Returns
Code Samples
local UserInputService = game:GetService("UserInputService")
if UserInputService.AccelerometerEnabled then
local acceleration = UserInputService:GetDeviceAcceleration().Position
print(acceleration)
else
warn("Cannot get device acceleration because device does not have an enabled accelerometer!")
end
GetDeviceGravity
Returns
Code Samples
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
Returns
Code Samples
local UserInputService = game:GetService("UserInputService")
if UserInputService.GyroscopeEnabled then
local _, cf = UserInputService:GetDeviceRotation()
print(cf)
else
warn("Cannot get device rotation because device does not have an enabled gyroscope!")
end
GetImageForKeyCode
Parameters
Returns
Code Samples
local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappedIconImage = UserInputService:GetImageForKeyCode(key)
imageLabel.Image = mappedIconImage
GetLastInputType
Returns
Code Samples
local UserInputService = game:GetService("UserInputService")
if UserInputService:GetLastInputType() == Enum.UserInputType.Keyboard then
print("Most recent input was keyboard!")
end
GetMouseButtonsPressed
Returns
Code Samples
local UserInputService = game:GetService("UserInputService")
UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
-- Return an array of the pressed mouse buttons
local buttonsPressed = UserInputService:GetMouseButtonsPressed()
local m1, m2 = false, false
for _, button in buttonsPressed do
if button.UserInputType == Enum.UserInputType.MouseButton1 then
print("MouseButton1 pressed!")
m1 = true
end
if button.UserInputType == Enum.UserInputType.MouseButton2 then
print("MouseButton2 pressed!")
m2 = true
end
if m1 and m2 then
print("Both mouse buttons pressed!")
end
end
end)
GetMouseDelta
Returns
Code Samples
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
local function onRenderStep()
local delta = UserInputService:GetMouseDelta()
if delta ~= Vector2.new(0, 0) then
print("The mouse has moved", delta, "since the last step")
end
end
RunService:BindToRenderStep("MeasureMouseMovement", Enum.RenderPriority.Input.Value, onRenderStep)
IsGamepadButtonDown
Parameters
Returns
RecenterUserHeadCFrame
Returns
Events
DeviceAccelerationChanged
Parameters
Code Samples
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
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceAccelerationChanged:Connect(changeAcceleration)
end
DeviceGravityChanged
Parameters
Code Samples
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
JumpRequest
Code Samples
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")
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
local processJumpRequest = false
local COOLDOWN_TIME = 0.5
local function jumpRequest()
if processJumpRequest == false then
processJumpRequest = true
-- Process custom jump request
print("Jump requested!")
-- Reset debounce variable after cooldown
task.wait(COOLDOWN_TIME)
processJumpRequest = false
end
end
UserInputService.JumpRequest:Connect(jumpRequest)
TextBoxFocusReleased
Parameters
Code Samples
local UserInputService = game:GetService("UserInputService")
local function textBoxFocused(textBox)
textBox.BackgroundTransparency = 0
end
local function textBoxFocusReleased(textBox)
textBox.BackgroundTransparency = 0.5
end
UserInputService.TextBoxFocused:Connect(textBoxFocused)
UserInputService.TextBoxFocusReleased:Connect(textBoxFocusReleased)
TextBoxFocused
Parameters
Code Samples
local UserInputService = game:GetService("UserInputService")
local function textBoxFocused(textBox)
textBox.BackgroundTransparency = 0
end
local function textBoxFocusReleased(textBox)
textBox.BackgroundTransparency = 0.5
end
UserInputService.TextBoxFocused:Connect(textBoxFocused)
UserInputService.TextBoxFocusReleased:Connect(textBoxFocusReleased)
TouchDrag
Parameters
TouchPan
Parameters
TouchPinch
Parameters
TouchRotate
Parameters
TouchSwipe
Parameters
WindowFocusReleased
Code Samples
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local awayEvent = ReplicatedStorage:WaitForChild("AwayEvent")
local function focusGained()
awayEvent:FireServer(false)
end
local function focusReleased()
awayEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local awayEvent = Instance.new("RemoteEvent")
awayEvent.Name = "AwayEvent"
awayEvent.Parent = ReplicatedStorage
local function manageForceField(player, away)
if away 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
awayEvent.OnServerEvent:Connect(manageForceField)