UserInputService

Visualizza obsoleti

*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.

Non costruibile
Assistenza
Non Replicato

UserInputService è un servizio utilizzato per rilevare e catturare i diversi tipi di input disponibili sul dispositivodi un utente.

Lo scopo principale di questo servizio è consentire alle esperienze di cooperare con più forme di input disponibili, come gamepad, schermi touch e tastiere.Consente a un LocalScript di eseguire diverse azioni a seconda del dispositivo e, a sua volta, fornire la migliore esperienza per l'utente finale.

Alcuni usi di questo servizio includono il rilevamento dell'input dell'utente quando interagiscono con interfacce utente, strumenti e altre istanze di gioco.Per rilevare l'input dell'utente, il servizio deve cercare un evento di servizio.Ad esempio, il servizio può rilevare eventi come quando l'utente tocca lo schermo di un dispositivo mobile utilizzando UserInputService.TouchStarted , o connette un gamepad come un controller Xbox al loro dispositivo utilizzando UserInputService.GamepadConnected .

Poiché questo servizio è solo lato client, funzionerà solo quando viene utilizzato in un LocalScript o in un ModuleScript richiesto da un LocalScript.Poiché UserInputService è solo lato client, gli utenti nel gioco possono rilevare solo il proprio input - e non l'input di altri.

Vedi anche ContextActionService , un servizio che ti consente di legare le funzioni a più input dell'utente.

Campioni di codice

The following example demonstrates one of many usage examples of handling a UserInputService event.

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)

Sommario

Proprietà

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive se il dispositivo dell'utente ha un accelerometro.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive se il dispositivo utilizzato da un utente ha un gamepad disponibile.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive se il dispositivo dell'utente ha un giroscopio.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive se il dispositivo dell'utente ha una tastiera disponibile.

  • Determina se il mouse dell'utente può essere spostato liberamente o è bloccato.

  • Non Replicato
    Lettura Parallela

    Scala l'output delta (cambio) dell'utente di Mouse .

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive se il dispositivo dell'utente ha un mouse disponibile.

  • MouseIcon:ContentId
    Lettura Parallela

    L'ID del contenuto dell'immagine utilizzata come Iconadel mouse dell'utente.

  • Lettura Parallela

    Determina se l'icona Mouse è visibile.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Determina la posizione della tastiera sullo schermo.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Determina la dimensione della tastiera sullo schermo.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive se una tastiera sullo schermo è attualmente visibile sullo schermo dell'utente.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Descrive se il dispositivo attuale dell'utente ha uno schermo touch disponibile.

  • Sola Lettura
    Non Replicato
    Lettura Parallela

    Indica se l'utente sta usando un casco di realtà virtuale.

Metodi

Eventi

Proprietà

AccelerometerEnabled

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se il dispositivo dell'utente ha un accelerometro

Un accelerometro è un componente trovato nella maggior parte dei dispositivi mobili che misura l'accelerazione (cambio di velocità).

Ad esempio, il seguente snippet di codice mostra come controllare se il dispositivo dell'utente ha un accelerometro.


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

Se il dispositivo ha un accelerometro abilitato, puoi ottenere la sua accelerazione attuale utilizzando la funzione UserInputService:GetDeviceAcceleration() o traccia quando l'accelerazione del Dispositivocambia utilizzando l'evento UserInputService.DeviceAccelerationChanged.

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Campioni di codice

This code adds a force on a part so that it falls in the direction of actual gravity relative to the user's device.

In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have an accelerometer.

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

This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.

The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:


camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *
currentRotation

The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.

The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.

Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.

In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.

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

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se il dispositivo utilizzato da un utente ha un gamepad disponibile.Se i gamepad sono disponibili, puoi usare UserInputService:GetConnectedGamepads() per recuperare un elenco di gamepad connessi.

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Vedi anche:

Campioni di codice

If you are using the default controls, you do not need to worry about this. If you're creating a custom script for handling gamepad controls, this is a good template for retrieving which gamepad enum you should use as the primary gamepad controller.

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

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se il dispositivo dell'utente ha un giroscopio.

Un giroscopio è un componente presente nella maggior parte dei dispositivi mobili che rileva l'orientamento e la velocità di rotazione.

Se il dispositivo di un utente ha un giroscopio, puoi incorporarlo nel tuo gioco utilizzando la funzione UserInputService:GetDeviceRotation() e l'evento UserInputService.DeviceRotationChanged.


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

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Campioni di codice

This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.

The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:


camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *
currentRotation

The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.

The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.

Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.

In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.

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

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se il dispositivo dell'utente ha una tastiera disponibile.Questa proprietà è true quando il dispositivo dell'utente ha una tastiera disponibile, e false quando non lo fa.

Può essere utilizzato per determinare se l'utente ha una tastiera disponibile - che può essere importante se vuoi controllare se puoi usare UserInputService:IsKeyDown() o UserInputService:GetKeysPressed() per controllare l'input della tastiera.

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Campioni di codice

This example prints "The user's device has an available keyboard!" if KeyboardEnabled is true and "The user's device does not have an available keyboard!" if KeyboardEnabled is false.

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

Lettura Parallela

Questa proprietà imposta come si comporta il mouse dell'utente in base all'enumero Enum.MouseBehavior. Può essere impostata su tre valori:

Il valore di questa proprietà non influisce sulla sensibilità del monitoraggio del movimento del mouse degli eventi.Ad esempio, GetMouseDelta restituisce la stessa posizione dello schermo Vector2 in pixel indipendentemente dal fatto che il mouse sia bloccato o sia in grado di muoversi liberamente intorno allo schermo dell'utente.Di Risultato, gli script predefiniti come quelli che controllano la fotocamera non sono interessati da questa Proprietà.

Questa proprietà viene sovrascritta se un GuiButton con Modal abilitato è GuiButton.Visible a meno che il pulsante destro del mouse del Giocatorenon sia giù.

Nota che, se il mouse è bloccato, UserInputService.InputChanged continuerà a fuocare quando il giocatore muove il mouse e passerà nel Delta in cui il mouse ha tentato di muoversi.Inoltre, se il giocatore viene espulso dalla Gioco, il mouse verrà sbloccato con forza.

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Campioni di codice

This example creates a binoculars script that decreases the player's FieldOfView() and MouseDeltaSensitivity() when a player with a MouseEnabled() left mouse clicks. The script also points the player's Camera towards the Vector3 world position of the mouse click.

When the player left mouse clicks again, the player's camera reverts back to the a custom Enum.CameraType with the same field of view and CFrame() as before the player zoomed in with the script.

While the player uses the binoculars, the script locks the player's mouse to the center of the screen by setting the player's MouseBehavior() to LockCenter. The player's camera moves when the player moves their mouse according to the InputObject.Delta property passed by InputChanged() indicating the mouse's Vector2 change in screen position.

In order for this example to work as expected, it should be placed in a LocalScript.

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

By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.

The script is broken into two parts:

  1. Mobile camera events, which rely on touch events
  2. Non-mobile camera events, which rely on keyboard input and tracking the user's movement

First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.

Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.

The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.

All of the parts discussed above are combined and shown in the code sample below.

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

Non Replicato
Lettura Parallela

Questa proprietà determina la sensibilità del Mouse dell'utente.

La sensibilità determina la portata in cui un movimento del mouse fisico si traduce in un movimento del mouse in gioco.Questo può essere utilizzato per regolare il modo in cui gli eventi sensibili tracciano il movimento del mouse, come GetMouseDelta , sono al movimento del mouse.

Questa proprietà non influisce sul movimento dell'Iconadel mouse.Né influisce sulla impostazione Sensibilità della fotocamera trovata nella scheda Impostazioni del menu Impostazioni del client, che regola anche la sensibilità del monitoraggio degli eventi del movimento del mouse.

Questa proprietà ha un valore massimo di 10 e un valore minimo di 0.Un valore più basso corrisponde a una minore sensibilità e un valore più alto a una maggiore sensibilità.

Quando la sensibilità è 0, gli eventi che tracciano il movimento del Topo, or mouse as computer mousecontinueranno a essere attivati ma tutti i parametri e le proprietà che indicano il cambiamento della posizione del mouse restituiranno Vector2.new() , o Vector3.new() nel caso di InputObject.Delta .Ad esempio, GetMouseDelta restituirà sempre (0, 0).

Campioni di codice

This example creates a binoculars script that decreases the player's FieldOfView() and MouseDeltaSensitivity() when a player with a MouseEnabled() left mouse clicks. The script also points the player's Camera towards the Vector3 world position of the mouse click.

When the player left mouse clicks again, the player's camera reverts back to the a custom Enum.CameraType with the same field of view and CFrame() as before the player zoomed in with the script.

While the player uses the binoculars, the script locks the player's mouse to the center of the screen by setting the player's MouseBehavior() to LockCenter. The player's camera moves when the player moves their mouse according to the InputObject.Delta property passed by InputChanged() indicating the mouse's Vector2 change in screen position.

In order for this example to work as expected, it should be placed in a LocalScript.

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

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se il dispositivo dell'utente ha un mouse disponibile.Questa proprietà è true quando il dispositivo dell'utente ha un Topo, or mouse as computer mousedisponibile, e false quando non lo ha.


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

È importante controllare questo prima di utilizzare le funzioni del mouse UserInputService come UserInputService:GetMouseLocation().

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Vedi anche:

Campioni di codice

This example creates a binoculars script that decreases the player's FieldOfView() and MouseDeltaSensitivity() when a player with a MouseEnabled() left mouse clicks. The script also points the player's Camera towards the Vector3 world position of the mouse click.

When the player left mouse clicks again, the player's camera reverts back to the a custom Enum.CameraType with the same field of view and CFrame() as before the player zoomed in with the script.

While the player uses the binoculars, the script locks the player's mouse to the center of the screen by setting the player's MouseBehavior() to LockCenter. The player's camera moves when the player moves their mouse according to the InputObject.Delta property passed by InputChanged() indicating the mouse's Vector2 change in screen position.

In order for this example to work as expected, it should be placed in a LocalScript.

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
Lettura Parallela

La proprietà MouseIcon determina l'immagine utilizzata come puntatore.Se vuoto, viene utilizzata una freccia predefinita.Mentre il cursore si posiziona su determinati oggetti UI come un ImageButton , TextButton , TextBox o ProximityPrompt , questa immagine verrà sovrascritta e ignorata temporaneamente.

Per nascondere completamente il cursore, non utilizzare un'immagine trasparente. Invece, imposta UserInputService.MouseIconEnabled su false.

Campioni di codice

This example changes the user mouse icon to look like a dragon image.

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

Lettura Parallela

Questa proprietà determina se l'icona Mouse è visibile quando true l'icona del Topo, or mouse as computer mouseè visibile, quando false non lo è.

Ad esempio, lo snippet del codice qui sotto nasconde l'Iconadel Topo, or mouse as computer mouse.


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

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Campioni di codice

This example hides the mouse icon while the player beings using their keyboard, such as to chat or enter text into a TextBox. The mouse icon reappears when the user resumes mouse input.

This uses the LastInputType() event to determine when the user begins keyboard input and mouse input - based on the value of the lastInputType argument.

In order for this example to work as expected, it should be placed in a LocalScript.

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

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive la posizione della tastiera sullo schermo in pixel. La posizione della tastiera è Vector2.new(0, 0) quando non è visibile.

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript o in un Script con RunContext impostato su Enum.RunContext.Client .

Vedi anche OnScreenKeyboardVisible e OnScreenKeyboardSize .

Campioni di codice

This example prints the position of the player's on-screen keyboard.

UserInputService.OnScreenKeyboardPosition

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

OnScreenKeyboardSize

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive la dimensione della tastiera sullo schermo in pixel. La dimensione della tastiera è Vector2.new(0, 0) quando non è visibile.

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript o in un Script con RunContext impostato su Enum.RunContext.Client .

Vedi anche OnScreenKeyboardVisible e OnScreenKeyboardPosition .

OnScreenKeyboardVisible

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se una tastiera sullo schermo è attualmente visibile sullo schermo dell'utente.

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript o in un Script con RunContext impostato su Enum.RunContext.Client .

Vedi anche OnScreenKeyboardSize e OnScreenKeyboardPosition .

TouchEnabled

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se il dispositivo attuale dell'utente ha uno schermo touch disponibile.

La proprietà viene utilizzata per determinare se il dispositivo dell'utente ha uno schermo touch e quindi se verranno Lanciareeventi touch.Se TouchEnabled è vero, puoi utilizzare eventi di UserInputService come UserInputService.TouchStarted e UserInputService.TouchEnded per tracciare quando un utente inizia e smette di toccare lo schermo del suo Dispositivo.

Il codice a blocchi seguente stampa se il dispositivo dell'utente ha uno schermo touch.


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

Vedi anche:

Campioni di codice

By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.

The script is broken into two parts:

  1. Mobile camera events, which rely on touch events
  2. Non-mobile camera events, which rely on keyboard input and tracking the user's movement

First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.

Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.

The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.

All of the parts discussed above are combined and shown in the code sample below.

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

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà descrive se l'utente sta utilizzando un Dispositivodi realtà virtuale (VR).

Se un dispositivo VR è abilitato, puoi interagire con la sua posizione e il suo movimento attraverso funzioni come UserInputService:GetUserCFrame() .Puoi anche reagire al movimento del dispositivo VR utilizzando l'evento UserInputService.UserCFrameChanged.


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

Poiché UserInputService è solo lato client, questa proprietà può essere utilizzata solo in un LocalScript .

Vedi anche:

Campioni di codice

This example demonstrates how to implement a head tracking script that mirrors the movement of a virtual reality (VR) headset (the user's actual head) to their in-game character's head.

The example first check if the user is using a VR device by checking the value of the VREnabled() property. This example only works if the user is using a VR headset.

To determine the initial CFrame of the character's head, the code sample calls GetUserCFrame() and passes Enum.UserCFrame.Head as the argument.

To update the head's CFrame whenever the user's VR headset moves, the example connects the VRService.UserCFrameChanged event to the TrackHead() function. When the event fires to indicate that a VR device moved, TrackHead() checks if the headset moved. If the headset moved, the function updates the CFrame of the character's head to the CFrame value provided as an argument.

As the UserCFrame enum also tracks VR left and right hand devices, the concept of VR device tracking can be expanded to other character bodyparts.

In order for the example to work as expected, it must be placed in a LocalScript.

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

Metodi

GamepadSupports

Questa funzione restituisce se il gamepad fornito Enum.UserInputType supporta un pulsante corrispondente al dato Enum.KeyCode.Questa funzione viene utilizzata per determinare gli input del gamepad validi.

Per determinare quali Enum.UserInputType gamepad sono connessi, usa UserInputService:GetConnectedGamepads() .

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

gamepadNum: Enum.UserInputType

Il Enum.UserInputType del gamepad.

Valore predefinito: ""
gamepadKeyCode: Enum.KeyCode

Il Enum.KeyCode del pulsante in questione.

Valore predefinito: ""

Restituzioni

Se il gamepad fornito supporta un pulsante corrispondente con il dato Enum.KeyCode.

Campioni di codice

This example binds the ButtonX key to action if it is supported by controller (Gamepad1). If bound, pressing the X Button invokes the action() function, which prints "Action".

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

Questa funzione restituisce un array di Enum.UserInputType gamepad attualmente connessi.Se non sono connessi gamepad, questo array sarà vuoto.Inoltre, restituisce solo oggetti UserInputType che sono gamepad.Ad esempio, questo evento restituirà un oggetto Gamepad1 connesso ma non un oggetto Keyboard.

Ad esempio, il seguente snippet di codice recupera i gamepad connessi e li memorizza in una variabile chiamata connectedGamepads.


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

Per controllare se un gamepad specifico è collegato, usa UserInputService:GetGamepadConnected() .

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:


Restituzioni

Un array di UserInputTypes corrispondente ai gamepad connessi al Dispositivodell'utente.

Campioni di codice

If you are using the default controls, you do not need to worry about this. If you're creating a custom script for handling gamepad controls, this is a good template for retrieving which gamepad enum you should use as the primary gamepad controller.

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

La funzione GetDeviceAcceleration determina l'accelerazione attuale del Dispositivodell'utente.Restituisce un InputObject che descrive l'accelerazione attuale del Dispositivo.

Perché ciò funzioni, il dispositivo dell'utente deve avere un accelerometro abilitato.Per controllare se il dispositivo di un utente ha un accelerometro abilitato, puoi controllare la ProprietàUserInputService.AccelerometerEnabled.

Se vuoi tracciare quando le modifiche dell'accelerazione del Dispositivodell'utente cambiano invece, puoi usare l'evento UserInputService.DeviceAccelerationChanged.

Poiché si attiva solo localmente, può essere utilizzato solo in un LocalScript .


Restituzioni

Campioni di codice

This example checks if a user's device has an enabled accelerometer. If it does, the example prints the current acceleration of the device. If not, the example prints:

Cannot get device acceleration because device does not have an enabled accelerometer!

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

Questa funzione restituisce un InputObject che descrive il vettorialedi gravità attuale del Dispositivo.

Il vector di gravità è determinato dall'orientamento del Dispositivorispetto alla forza di gravità del mondo reale.Ad esempio, se un dispositivo è perfettamente in piedi (portrait), il vector di gravità è Vector3.new(0, 0, -9.18) .Se il lato sinistro del dispositivo punta verso il basso, il vector è Vector3.new(9.81, 0, 0).Infine, se la parte posteriore del dispositivo punta verso il basso, il vector è Vector3.new(0, -9.81, 0).

Questa funzione potrebbe essere utilizzata per abilitare il dispositivo dell'utente ad impattare o controllare la gravità all'interno del gioco o spostare oggetti in gioco come una palla.

La gravità viene tracciata solo per i giocatori che utilizzano un dispositivo con un giroscopio abilitato - come un Dispositivomobile.

Per controllare se il dispositivo di un utente ha un giroscopio abilitato, controlla il valore di UserInputService.GyroscopeEnabled .Se il dispositivo ha un giroscopio abilitato, puoi anche utilizzare l'evento UserInputService.DeviceGravityChanged per tracciare quando la forza di gravità sul dispositivo dell'utente cambia.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .


Restituzioni

Campioni di codice

Using the Gyroscope gives us the down direction for the player's device. We can use this to move objects in the game world. This example implements a level where the bubble will move along the X and Z axes depending on the device's current gryoscope position in X and Z.

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

Questa funzione restituisce un InputObject e un CFrame che descrive il vettorialedi rotazione attuale del Dispositivo.

Questo viene sparato con un InputObject.La proprietà Posizione dell'oggetto di input è una Enum.InputType.Gyroscope che traccia la rotazione totale in ogni asse locale del dispositivo.

La rotazione del dispositivo può essere tracciata solo su dispositivi con un gyroscope .

Poiché questa funzione si attiva localmente, può essere utilizzata solo in un LocalScript .


Restituzioni

Un tuple che contiene due proprietà:

  1. La proprietà delta descrive la quantità di rotazione che è stata l'ultima
  2. Il CFrame è la rotazione attuale del Dispositivorispetto al suo quadro di riferimento predefinito.

Campioni di codice

This example prints the current CFrame of a players device. Note that this will only work as expected if the player's device has an enabled gyroscope. If not, the example prints:

Cannot get device rotation because device does not have an enabled gyroscope!

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

Questa funzione restituisce il TextBox il client è attualmente focalizzato su.Un TextBox può essere selezionato manualmente dall'utente, o la selezione può essere forzata utilizzando la funzione TextBox:CaptureFocus().Se non viene selezionata alcuna TextBox, questa funzione restituirà nil .

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche

Restituzioni

GetGamepadConnected

Questa funzione restituisce se un gamepad con il dato Enum.UserInputType è connesso al client.

Questo può essere utilizzato per verificare se un gamepad specifico, come 'Gamepad1' è connesso al Dispositivodel client.

Per recuperare un elenco di tutti i gamepad connessi, usa UserInputService:GetConnectedGamepads() .

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

gamepadNum: Enum.UserInputType

Il Enum.UserInputType del gamepad in questione.

Valore predefinito: ""

Restituzioni

Se un gamepad associato a Enum.UserInputType è connesso.

Campioni di codice

This example returns whether Gamepad1 is connected to the client. It will print true if Gamepad1 is connected and false if Gamepad1 is not connected.

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

Questa funzione restituisce un array di per tutti gli input disponibili sul gamepad dato, che rappresenta l'ultimo stato di input di ciascun input.

Per trovare il UserInputTypes dei gamepad connessi, usa UserInputService:GetConnectedGamepads() .

Poiché questa funzione si attiva solo localmente, può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

gamepadNum: Enum.UserInputType

Il Enum.UserInputType corrispondente con il gamepad in questione.

Valore predefinito: ""

Restituzioni

Un array di InputObjects che rappresenta lo stato attuale di tutti gli input disponibili per il gamepad specificato.

GetImageForKeyCode

ContentId

Questo metodo prende il richiesto Enum.KeyCode e restituisce l'immagine associata per il dispositivo gamepad connesso attualmente (limitato a Xbox, PlayStation e Windows).Questo significa che se il controller connesso è un controller Xbox One, l'utente vede le risorse di Xbox.Allo stesso modo, se il dispositivo connesso è un controller PlayStation, l'utente vede le risorse di PlayStation.Se vuoi utilizzare risorse personalizzate, vedi GetStringForKeyCode() .

Parametri

keyCode: Enum.KeyCode

Il Enum.KeyCode per il quale recuperare l'immagine associata.

Valore predefinito: ""

Restituzioni

ContentId

L'ID risorsa immagine restituita.

Campioni di codice

This API returns the requested image for the given Enum.KeyCode.

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

Questa funzione restituisce un array di InputObjects associato alle chiavi attualmente premuto.

Questo array può essere iterato per determinare quali tasti sono attualmente premuti, utilizzando i valori InputObject.KeyCode .

Per controllare se viene premuta una chiave specifica, usa UserInputService:IsKeyDown() .

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .


Restituzioni

Un array di InputObjects associato alle chiavi attualmente premuti.

Campioni di codice

This example demonstrates how to use the UserInputService:GetKeysPressed() function to create a combo action where the player double jumps when the player presses actionKey key (Left Shift) + Jump key (Spacebar).

The actionKey variable indicates which key, combined with the Jump key, needs to be pressed for the player to double jump.

When the player presses the Jump key, the JumpRequest() event is invoked, which is connected to the script's jumpRequest function. If the Left Shift key is pressed and the player is not already in the middle of a jump, this function sets the canDoubleJump boolean to true.

The example connects the stateChanged function to the StateChanged() event so that the function fires when their humanoid's state changes. If the state changes from Jumping to Freefall, and the canDoubleJump boolean is true, the function makes the player jump again by setting their humanoid's state back to Jumping using the ChangeState() function . The example also uses the canJump boolean variable to determine when the player is in the middle of a jump. Without this variable, the player could press the actionKey + Jump Key (spacebar) to jump endlessly without landing. When the boolean is true, the player is not jumping. If the player is not jumping, jumpRequest() checks if the actionKey is pressed and sets canJump to false. When the player lands, stateChanged() sets the variable to true.

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

Questa funzione restituisce 'Enum.UserInputType` associato all'ultimo input dell'utente.

Ad esempio, se l'input precedente dell'utente avesse premuto la barra spaziatrice, il Enum.UserInputType restituito sarebbe stato 'Tastiera' .

L'evento UserInputService.LastInputTypeChanged può essere utilizzato per tracciare quando l'ultimo Enum.UserInputType utilizzato dall'utente cambia.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .


Restituzioni

Il Enum.UserInputType associato all'ultimo input dell'utente.

Campioni di codice

This example gets the last input type and indicates if it was keyboard input.

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

Questa funzione restituisce un array di InputObjects corrispondente ai pulsanti del mouse attualmente premuti.

I pulsanti del mouse che vengono tracciati da questa funzione includono:


<td>Descrizione</td>
</tr>
</thead>
<tr>
<td>Pulsante del mouse1</td>
<td>Il pulsante sinistro del mouse.</td>
</tr>
<tr>
<td>Tasto del mouse 2</td>
<td>Il pulsante destro del mouse.</td>
</tr>
<tr>
<td>Tasto del mouse 3</td>
<td>Il pulsante centrale del mouse.</td>
</tr>
Nome

Se l'utente non sta premendo alcun pulsante del mouse quando viene chiamata la funzione, restituirà un vettorevuoto.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .


Restituzioni

Un array di InputObjects corrispondente ai pulsanti del mouse attualmente tenuti premuti.

Campioni di codice

This example checks if the user pressed MouseButton1, MouseButton2, or both mouse buttons on InputBegan().

The example can be extended to behave differently depending on which mouse buttons are pressed.

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

Questa funzione restituisce il cambiamento, in pixel, della posizione del Giocatoredi Mouse nella ultima cornice renduta come Vector2 .Questa funzione funziona solo se il mouse è stato bloccato utilizzando la ProprietàUserInputService.MouseBehavior.Se il mouse non è stato bloccato, i valori restituiti Vector2 saranno zero.

La sensibilità del Topo, or mouse as computer mouse, determinata nelle impostazioni del client e UserInputService.MouseDeltaSensitivity , influirà sul Risultato.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .


Restituzioni

Cambio nel movimento del Topo, or mouse as computer mouse.

Campioni di codice

GetMouseDelta returns the current change in movement of the mouse as a Vector2, but only if the mouse is locked. If the mouse isn't locked the values in the returned Vector2 will be zero. It measures any mouse movement in pixels from the last render step to the current render step. If the user has set their camera sensitivity to be higher or lower than 1 in the in-game menu this will affect the value returned by GetMouseDelta. The camera sensitivity is a multiplier to the amount the camera moves as a result of mouse input.

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)

By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.

The script is broken into two parts:

  1. Mobile camera events, which rely on touch events
  2. Non-mobile camera events, which rely on keyboard input and tracking the user's movement

First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.

Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.

The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.

All of the parts discussed above are combined and shown in the code sample below.

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

Questa funzione restituisce un Vector2 che rappresenta la posizione dello schermo attuale del GiocatoreMouse in pixel rispetto all'angolo superiore sinistro.Questo non tiene conto degli inserimenti Enum.ScreenInsets ; per ottenere quelli superiori a sinistra e inferiori a destra, chiama GuiService:GetGuiInset() .

Se la posizione del puntatore del mouse è fuori schermo o il dispositivo del Giocatorenon ha un Topo, or mouse as computer mouse, il valore restituito sarà non determinato.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .


Restituzioni

Un Vector2 che rappresenta la posizione attuale dello schermo del Topo, or mouse as computer mouse, in pixel.

Campioni di codice

This example binds the moveToMouse() to RunService's RenderStep to move the GUI to the location of the player's mouse. It does this by converting the location, a Vector2, into a UDim2.

The example sets the value of the GUI's parent ScreenGui ScreenGui.IgnoreGuiInset property to false force the GUI Inset imposed by Roblox's CoreGuis to be ignored by the ScreenGui and its descendants

In order for this example to work as expected, it should be placed in a LocalScript that is a child of the GUI being moved to the mouse's location.

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

Questa funzione restituisce un array di gamepad UserInputTypes che sono connessi e abilitati per la navigazione GUI.Questa lista è in ordine decrescente di priorità, il che significa che può essere iterata per determinare quale gamepad debba avere il controllo della navigazione.

Se un gamepad connesso è un gamepad di navigazione solo determina quale gamepad(s) controlla le interfacce utente di navigazione.Questo non influisce sui Controllidi navigazione.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:


Restituzioni

Un array di UserInputTypes che può essere utilizzato per la navigazione GUI, in ordine decrescente di priorità.

GetStringForKeyCode

GetStringForKeyCode restituisce una stringa che rappresenta una chiave che l'utente deve premere per inserire un dato Enum.KeyCode , tenendo presente la loro disposizione della tastiera.Per i codici chiave che richiedono che venga tenuto premuto qualche modificatore, questa funzione restituisce la chiave da premere in aggiunta al modificatore.Vedi gli esempi seguenti per una ulteriore spiegazione.

Quando si utilizza Roblox con una tastiera non QWERTY, i codici delle chiavi vengono mappati alle posizioni equivalenti di QWERTY.Ad esempio, premere A su una tastiera AZERTY produce Enum.KeyCode.Q .Questa mappatura può portare a informazioni non corrispondenti sugli elementi dell'interfaccia utente dell'esperienza.Ad esempio, "Premi M per aprire la mappa" è inaccurato su una tastiera AZERTY; dovrebbe essere "Premi ? per aprire la mappa" che è nella stessa posizione di M su QWERTY.Questa funzione risolve questo problema fornendo la chiave effettiva da premere mentre si usano layout di tastiera non QWERTY.


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

<th>Valore di restituzione</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.Q</code></td>
<td><code>Q</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.W</code></td>
<td><code>W</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Equals</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>2</code> perché <code>@</code> è digitato con <kbd>Shift</kbd><kbd>2</kbd></td>
</tr>
</tbody>
Codice Chiave
Esempi sulla tastiera AZERTY

<th>Valore di restituzione</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.Q</code></td>
<td><code>A</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.W</code></td>
<td><code>Z</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Equals</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>É</code></td>
</tr>
</tbody>
Codice Chiave
Uso del gamepad

GetStringForKeyCode() restituisce la mappatura della stringa per il Enum.KeyCode per il gamepad più recentemente connesso.Se il controller connesso non è supportato, la funzione restituisce la conversione della stringa predefinita per il codice chiave richiesto.

L'esempio seguente mostra come puoi mappare risorse personalizzate per 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
Mappature del gamepad

I codici della tastiera direzionale non hanno differenze basate sul Dispositivo.Enum.KeyCode.ButtonSelect ha un comportamento leggermente diverso in alcuni casi.Usa entrambe le mappature di PlayStation per garantire agli utenti di vedere i pulsanti corretti.


<th>Valore di restituzione della PlayStation</th>
<th>Valore di restituzione Xbox</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.ButtonA</code></td>
<td><code>PulsanteCross</code></td>
<td><code>PulsanteA</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonB</code></td>
<td><code>Cerchio di pulsanti</code></td>
<td><code>PulsanteB</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonX</code></td>
<td><code>Square del pulsante</code></td>
<td><code>PulsanteX</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonY</code></td>
<td><code>Triangolo di pulsante</code></td>
<td><code>PulsanteY</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonL1</code></td>
<td><code>Pulsante L1</code></td>
<td><code>PulsanteLB</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonL2</code></td>
<td><code>PulsanteL2</code></td>
<td><code>PulsanteLT</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonL3</code></td>
<td><code>Pulsante L3</code></td>
<td><code>PulsanteLS</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonR1</code></td>
<td><code>Pulsante R1</code></td>
<td><code>PulsanteRB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR2</code></td>
<td><code>Pulsante R2</code></td>
<td><code>PulsanteRT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR3</code></td>
<td><code>Pulsante R3</code></td>
<td><code>PulsanteRS</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonStart</code></td>
<td><code>Opzioni di pulsante</code></td>
<td><code>PulsanteInizia</code></td>
</tr>
<tr>
<td><code>Enumerazione.KeyCode.ButtonSelect</code></td>
<td><code>Touchpad dei pulsanti</code> e <code>Condividi pulsante</code></td>
<td><code>PulsanteSelezione</code></td>
</tr>
</tbody>
Codice Chiave
Immagini di sistema per KeyCodes

Quando si utilizza un Enum.KeyCode che può essere meglio rappresentato come un'immagine, come per un ImageLabel in un'interfaccia utente, puoi utilizzare le seguenti icone legacy.Tuttavia, si consiglia di utilizzare GetImageForKeyCode() come metodo più moderno e cross‑platform per recuperare le icone del controller Xbox e PlayStation.


<th>Immagine</th>
<th>ID risorsa</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxX.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxX.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonY</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxY.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/xboxY.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonA</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxA.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxA.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonB</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/xboxB.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadLeft</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadLeft.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/dpadLeft.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadRight</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadRight.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/dpadRight.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadUp</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadUp.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/dpadUp.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadDown</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadDown.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/dpadDown.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonSelect</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxView.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxView.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonStart</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxmenu.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxmenu.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/xboxLB.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRB.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLT.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxLT.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRT.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRT.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL3</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLS.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxLS.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR3</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRS.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRS.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Thumbstick1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLSDirectional.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxLSDirectional.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Thumbstick2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRSDirectional.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRSDirectional.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Backspace</code></td>
<td>
<img src="../../../assets/scripting/controls/backspace.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/backspace.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Return</code></td>
<td>
<img src="../../../assets/scripting/controls/return.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/return.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.LeftShift</code></td>
<td>
<img src="../../../assets/scripting/controls/shift.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/shift.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.RightShift</code></td>
<td>
<img src="../../../assets/scripting/controls/shift.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/shift.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Tab</code></td>
<td>
<img src="../../../assets/scripting/controls/tab.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/tab.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Quote</code></td>
<td>
<img src="../../../assets/scripting/controls/apostrophe.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/apostrophe.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Comma</code></td>
<td>
<img src="../../../assets/scripting/controls/comma.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controlli/comma.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Backquote</code></td>
<td>
<img src="../../../assets/scripting/controls/graveaccent.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/graveaccent.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Period</code></td>
<td>
<img src="../../../assets/scripting/controls/period.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/period.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Space</code></td>
<td>
<img src="../../../assets/scripting/controls/spacebar.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/spacebar.png</code></td>
</tr>
</tbody>
Codice Chiave

Parametri

keyCode: Enum.KeyCode
Valore predefinito: ""

Restituzioni

GetSupportedGamepadKeyCodes

Questa funzione restituisce un array di KeyCodes che il gamepad associato al dato Enum.UserInputType supporta.

Questa funzione può essere utilizzata per determinare quali KeyCodes sono supportati e non supportati da un gamepad connesso.Per determinare se un codice chiave specifico è supportato, usa UserInputService:GamepadSupports() .

Se chiamato su un gamepad non esistente o non connesso, questa funzione restituirà un vettorevuoto.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

gamepadNum: Enum.UserInputType

Il Enum.UserInputType del gamepad.

Valore predefinito: ""

Restituzioni

Un array di KeyCodes supportato dal gamepad fornito.

Campioni di codice

This example gets a list of navigation gamepads and a list of their supported Enum.KeyCodes. Then, it iterates through the supported KeyCode list and binds the ButtonX and X keys to functions if they are supported by a gamepad using the ContextActionService.

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

Questa funzione controlla se un particolare pulsante viene premuto su un particolare gamepad.Restituisce true se il gamepad ha premuto il button specificato, altrimenti restituisce false.

Tipi di input utente validi

Il gamepad specificato dovrebbe essere uno dei seguenti valori dell'Enum UserInputType:


<tr>
<td>Enumerazione.UserInputType.Gamepad1-8</td>
</tr>
Nome
Tasti di scelta validi

Il pulsante specificato dovrebbe essere uno dei seguenti valori dell'elenco KeyCredentials:


<tr>
<td>Enumerazione.KeyCode.ButtonX</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonY</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonA</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonB</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonR1</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonL1</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR2</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonL2</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR3</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonL3</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonStart</td>
</tr>
<tr>
<td>Enumerazione.KeyCode.ButtonSelect</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadLeft</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadRight</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadUp</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadDown</td>
</tr>
Nome

Questo può essere utilizzato per verificare se un pulsante specifico, come A, è tenuto premuto. Ad esempio:


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

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

gamepadNum: Enum.UserInputType

Il Enum.UserInputType della gamepad data.

Valore predefinito: ""
gamepadKeyCode: Enum.KeyCode

Il Enum.KeyCode del pulsante specificato.

Valore predefinito: ""

Restituzioni

Se il pulsante del gamepad specificato sul gamepad fornito viene premuto è premuto.

Campioni di codice

This example uses the UserInputService:IsGamepadButtonDown() function to create different behaviors when the X gamepad button is pressed than when a X button is not pressed when user input UserInputBegan|begins.

The local function IsGamepadXDown() returns whether the X gamepad button is down. This function checks if the X button is down for the activeGamepad, which is set by GetActiveGamepad. The GetActiveGamepad() fnction finds the lowest numbered navigation gamepad, connected gamepad, or gamepad1 if there are no navigation or connected gamepads.

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

Questa funzione restituisce se l'utente sta tenendo premuto il tasto associato alla chiave data Enum.KeyCode .Restituisce true se viene premuta la chiave specificata o false se non viene premuta.

Questo può essere utilizzato per controllare se viene premuta una chiave specifica, come la barra spaziatrice. Ad esempio:


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

Per recuperare un elenco di tutte le chiavi premuto dall'utente, usa la funzione UserInputService:GetKeysPressed().

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

keyCode: Enum.KeyCode

Il Enum.KeyCode della chiave.

Valore predefinito: ""

Restituzioni

Se la chiave specificata viene tenuta premuta.

Campioni di codice

This example uses the UserInputService:IsKeyDown() function to create different behaviors when a shift key is held down than when a shift key is not held down when user input UserInputBegan|begins.

The local function IsShiftKeyDown() returns whether the left or right shift keys are pressed.

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

Questa funzione prende un pulsante del mouse Enum.UserInputType e restituisce un bool che indica se è attualmente premuto.

Il pulsante del mouse controllato dipende dal valore Enum.UserInputType passato alla funzione come argomento. Ad esempio:


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

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript."

Parametri

mouseButton: Enum.UserInputType

Il Enum.UserInputType del pulsante del mouse.

Valore predefinito: ""

Restituzioni

Se il pulsante del mouse fornito è attualmente tenuto premuto.

Campioni di codice

By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.

The script is broken into two parts:

  1. Mobile camera events, which rely on touch events
  2. Non-mobile camera events, which rely on keyboard input and tracking the user's movement

First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.

Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.

The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.

All of the parts discussed above are combined and shown in the code sample below.

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

Questa funzione restituisce true se il gamepad specificato Enum.UserInputType è autorizzato a controllare la navigazione e la selezione GuiObjects .

Se vuoi impostare un gamepad di navigazione, puoi usare UserInputService:SetNavigationGamepad() . Puoi anche usare UserInputService:GetNavigationGamepads() per ottenere un elenco di tutti i gamepad di navigazione.

Ad esempio, il codice seguente controlla se il gamepad1 è come un gamepad di navigazione:


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

Un elenco di tutti i gamepad connessi, indipendentemente dalla navigazione, può essere recuperato utilizzando `UserInput/GetConnectedGamepads.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

gamepadEnum: Enum.UserInputType

Il Enum.UserInputType della gamepad specificata.

Valore predefinito: ""

Restituzioni

Se il gamepad specificato è un gamepad di navigazione.

RecenterUserHeadCFrame

()

Questa funzione riposiziona il CFrame della cuffia VR all'orientamento attuale della cuffia indossata dall'utente.Questo significa che l'orientamento attuale del casco è impostato su CFrame.new() .

Usa questa funzione per spostare il casco CFrame al centro dell'area di riproduzione se sembra essere a uno strano Dislocamento.

Questo si comporta identicamente alla funzione VRService , VRService:RecenterUserHeadCFrame() .

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .


Restituzioni

()

Campioni di codice

This example fires the function to recenter the CFrame of the user's head to the current location of the VR headset being worn by the user.

UserInputService:RecenterUserHeadCFrame

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

SetNavigationGamepad

()

La funzione SetNavigationGamepad imposta se il gamepad specificato Enum.UserInputType può spostare il navigatore GUI.Un gamepad che è autorizzato a muovere il navigatore GUI è considerato un gamepad di navigazione.

Se l'argomento abilitato viene passato come true, il Gamepad può spostare il navigatore GUI.Se l'argomento è false, il Gamepad non può spostare il navigatore GUI.

Se vuoi controllare se un Gamepad specificato è impostato per essere un gamepad di navigazione, puoi usare la funzione UserInputService:IsNavigationGamepad().Puoi anche usare il UserInputService:GetNavigationGamepads() per recuperare un elenco di tutti i gamepad di navigazione.

Poiché UserInputService è solo lato client, questa funzione può essere utilizzata solo in un LocalScript .

Vedi anche:

Parametri

gamepadEnum: Enum.UserInputType

Il Enum.UserInputType della gamepad specificata.

Valore predefinito: ""
enabled: boolean

Se il gamepad specificato può spostare il navigatore GUI.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

This example sets Gamepad1 as a navigation gamepad by passing Enum.UserInputType.Gamepad1 and true as arguments.

UserInputService:SetNavigationGamepad

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

Eventi

DeviceAccelerationChanged

L'evento DeviceAccelerationChanged si attiva quando un utente sposta un dispositivo che ha un accelerometro.

Un accelerometro è un componente trovato nella maggior parte dei dispositivi mobili che misura l'accelerazione (cambio di velocità).

Per determinare se il dispositivo di un utente ha un accelerometro abilitato, vedi UserInputService.AccelerometerEnabled .

Questo evento può essere utilizzato per tracciare il movimento di un dispositivo che ha un accelerometro.Un uso di esempio include la movimentazione del personaggio del giocatore quando un dispositivo mobile si accelera.

Inoltre, questo evento può essere utilizzato insieme a UserInputService:GetDeviceAcceleration() per determinare il movimento attuale del dispositivo di un utente se il dispositivo ha un accelerometro.

Questo evento si attiva solo localmente - il che significa che solo il giocatore il cui dispositivo si muove può utilizzare l'evento e funzionerà solo in un LocalScript .

Parametri

acceleration: InputObject

Un InputObject , con un UserInputType di 'Accelerometro' e Position che mostra la forza della gravità su ogni asse locale del dispositivo.


Campioni di codice

This example uses the accelerometer to move the player character when a mobile device is accelerated. The character will move along the axis that the device was moved.

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

L'evento si attiva quando la gravità del Dispositivocambia su un dispositivo che ha un accelerometro.

Il vector di gravità di un Dispositivorappresenta la forza di gravità su ciascuno degli assi X, Y e Z del Dispositivo.Mentre la gravità non cambia mai, la forza che esercita su ogni asse cambia quando il dispositivo ruota e cambia orientamento.Il valore della forza esercitata su ciascun asse è un vector unitario che va da -1 a 1.

Un accelerometro è un componente trovato nella maggior parte dei dispositivi mobili che misura l'accelerazione (cambio di velocità).

Questo evento può essere utilizzato per determinare la direzione del mondo reale della forza di gravità su un Dispositivodell'utente.Questo può poi essere utilizzato per simulare la forza di gravità su un dispositivo dell'utente all'interno del Gioco, come su oggetti in gioco (vedi esempio qui sotto).

Per controllare se il dispositivo di un utente ha un accelerometro abilitato, vedi UserInputService.AccelerometerEnabled .Se il dispositivo ha un accelerometro abilitato, puoi usare la funzione UserInputService:GetDeviceGravity() per ottenere la forza attuale della gravità sul Dispositivodell'utente.

Parametri

gravity: InputObject

Un InputObject , con una proprietà InputObject.Position che mostra la forza della gravità su ogni asse locale del dispositivo.Questa posizione può essere utilizzata come direzione per determinare la direzione della gravità rispetto al Dispositivo.


Campioni di codice

This code adds a force on a part so that it falls in the direction of actual gravity relative to the user's device.

In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have an accelerometer.

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

This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.

The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:


camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *
currentRotation

The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.

The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.

Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.

In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.

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

L'evento DeviceRotationChanged si attiva quando un utente ruota un dispositivo che ha un accelerometro.

Un giroscopio è un componente presente nella maggior parte dei dispositivi mobili che rileva l'orientamento e la velocità di rotazione.

L'evento è utile per tracciare l'orientamento del dispositivo e come cambia quando l'utente ruota il suo Dispositivo.Per determinare la rotazione del dispositivo attuale, puoi usare la funzione UserInputService:GetDeviceRotation().

Per verificare se il dispositivo di un utente ha un giroscopio abilitato e che questo evento verrà Lanciare, vedi UserInputService.GyroscopeEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Parametri

rotation: InputObject

Un InputObject che fornisce informazioni sulla rotazione del Dispositivo.InputObject.Position rappresenta la nuova rotazione un valore posizionale Vector3 e InputObject.Delta rappresenta il cambio di rotazione in un valore posizionale Vector3.

cframe: CFrame

Un CFrame che rappresenta l'orientamento attuale del Dispositivo.


Campioni di codice

This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.

The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:


camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *
currentRotation

The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.

The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.

Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.

In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.

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

This code adds a force on a part so that it falls in the direction of actual gravity relative to the user's device.

In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have an accelerometer.

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

L'evento GamepadConnected si attiva quando un gamepad viene connesso al client.

Poiché un gioco Roblox supporta più controller, questo evento è utile quando viene abbinato all'evento UserInputService.GamepadDisconnected per tracciare quali controller/gamepad sono attivi.Puoi anche usare UserInputService:GetConnectedGamepads() per trovare il giusto gamepad da utilizzare.

L'esempio seguente mostra un esempio di utilizzo di una traccia quando un gamepad è connesso al client.


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

Se vuoi vedere quali dispositivi sono connessi, puoi usare la funzione UserInputService:GetConnectedGamepads().

Poiché questo evento si attiva localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

gamepadNum: Enum.UserInputType

Il Enum.UserInputType della gamepad connessa.


GamepadDisconnected

L'evento GamepadDisconnected si attiva quando un gamepad viene disconnesso.

Poiché un gioco Roblox supporta più controller, questo evento è utile quando viene abbinato all'evento UserInputService.GamepadConnected per tracciare quali controller/gamepad sono attivi.Puoi anche usare UserInputService:GetConnectedGamepads() per trovare il giusto gamepad da utilizzare.

L'esempio seguente mostra un esempio di utilizzo di una traccia quando un gamepad viene disconnesso dal client.


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

Poiché questo evento si attiva localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

gamepadNum: Enum.UserInputType

Il Enum.UserInputType del gamepad disconnesso.


InputBegan

L'evento InputBegan si attiva quando un utente inizia a interagire tramite un dispositivo Interfaccia uomo-computer (pulsante del mouse verso il basso, tocco di inizio, pulsante della tastiera verso il basso, ecc.).

Può essere utilizzato per tracciare l'inizio dell'interazione dell'utente, come quando un utente interagisce per la prima volta con un elemento GUI, un gamepad, ecc.Non cattura i movimenti della ruota del mouse.

Questo evento può essere utilizzato insieme a UserInputService.InputChanged e UserInputService.InputEnded per tracciare quando inizia l'input dell'utente, le modifiche e finisce.

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Parametri

Un'esempioInputObject che contiene informazioni sull'input dell'utente.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The following example demonstrates one of many usage examples of handling user input from InputBegan depending on its type.

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

L'evento InputChanged si attiva quando un utente cambia il modo in cui interagisce attraverso un dispositivo Interfaccia uomo-computer (pulsante del mouse verso il basso, tocco di inizio, pulsante della tastiera verso il basso, ecc.).

Per ignorare gli eventi che vengono gestiti automaticamente da Roblox, come lo scrolling in un ScrollingFrame, controlla che l'argomento gameProcessedEvent sia falso.Questo evento può essere utilizzato insieme a UserInputService.InputBegan e UserInputService.InputEnded per tracciare quando inizia l'input dell'utente, le modifiche e finisce.

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Parametri

Un'esempioInputObject che contiene informazioni sull'input dell'utente.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The following example demonstrates one of many usage examples of handling user input from InputChanged depending on its type.

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

L'evento InputEnded si attiva quando un utente smette di interagire tramite un dispositivo di interfaccia uomo-computer (tasto del mouse giù, tocco inizio, pulsante della tastiera giù, ecc.).Questo è utile quando si traccia quando un utente rilascia una tastiera, un pulsante del mouse, un input touchscreen, ecc.

Questo evento può essere utilizzato insieme a UserInputService.InputBegan e UserInputService.InputChanged per tracciare quando inizia l'input dell'utente, le modifiche e finisce.

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Parametri

Un'esempioInputObject che contiene informazioni sull'input dell'utente.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The following example demonstrates one of many usage examples of handling user input from InputEnded depending on its type.

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

L'evento JumpRequest UserInputService si attiva quando c'è una richiesta di salto dal client, ad esempio quando il client premere la barra spaziatrice o il pulsante di salto su mobile.

Questo evento si attiva ogni volta che l'utente tenta di fare il suo Salta.Il comportamento predefinito risponde a una richiesta di salto impostando la proprietà del GiocatoreHumanoid.Jump a vero, che fa Saltail personaggio del Giocatore.

L'evento può essere utilizzato per tracciare ogni volta che un giocatore vuole Salta.Invece di utilizzarlo per far Saltaun giocatore, questo dovrebbe essere utilizzato per cambiare il comportamento di salto predefinito - come disabilitare il salto.

Ad esempio, il codice seguente stampa "Jump" ogni volta che il giocatore invia una Richiestadi salto.


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

Poiché questo evento si attiva più volte per una singola Richiestadi salto, è consigliato utilizzare un debounce.

Se desideri connettere le chiavi o i pulsanti ad altre azioni, considera l'uso di eventi come UserInputService:GetKeysPressed() e UserInputService.InputBegan o il ContextActionService.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .


Campioni di codice

This code sample disables jumping for the LocalPlayer by setting the Enum.HumanoidStateType.Jumping state to false. Setting this state to false as soon as the user tries to jump cancels the jump.

In order for this example to work as expected, it should be placed in a LocalScript.

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

L'evento UserInputService.LastInputTypeChanged si attiva ogni volta che il cliente cambia il modo in cui interagisce attraverso un DispositivoInterfaccia Uomo-Computer.(i.e.da MouseMovement a MouseWheel o da Thumbstick1 a Thumbstick2).

Per ottenere il valore dell'ultimo inserisci / scrividi input, indipendentemente dal fatto che sia cambiato o meno, puoi usare la funzione UserInputService:GetLastInputType().

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Parametri

lastInputType: Enum.UserInputType

Un Enum.UserInputType che indica l'ultimo inserisci / scrividi input.


Campioni di codice

This example hides the mouse icon while the player beings using their keyboard, such as to chat or enter text into a TextBox. The mouse icon reappears when the user resumes mouse input.

This uses the LastInputType() event to determine when the user begins keyboard input and mouse input - based on the value of the lastInputType argument.

In order for this example to work as expected, it should be placed in a LocalScript.

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 si attiva quando l'utente esegue un'azione puntatore specifica. In particolare, scorrendo la ruota del mouse.

Parametri

wheel: number
pan: Vector2
pinch: number
gameProcessedEvent: boolean

TextBoxFocusReleased

L'evento TextBoxFocusReleased si attiva quando un client perde il focus su un TextBox , tipicamente quando un client interrompe l'inserimento del testo premendo il ritorno o cliccando/toccando altrove sullo schermo.

Ad esempio, il codice seguente stampa il nome del TextBox perdendo il focus quando si attiva l'evento.


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

Può essere utilizzato insieme a UserInputService.TextBoxFocused per tracciare quando un TextBox guadagna e perde focus.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche

Parametri

textboxReleased: TextBox

Il TextBox che ha perso il focus.


TextBoxFocused

Questo evento si attiva quando un guadagno si concentra su un TextBox, tipicamente quando un cliente fa clic/tocca su una casella di testo per iniziare l'input di testo.Questo si attiva anche se un focus della casella di testo è focalizzato utilizzando TextBox:CaptureFocus() .

Ad esempio, il codice seguente stampa il nome del TextBox focalizzato quando si attiva l'evento.


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

Può essere utilizzato insieme a UserInputService.FocusReleased per tracciare quando una casella di testo guadagna e perde focus.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche

Parametri

textboxFocused: TextBox

Il TextBox che ha guadagnato focus.


TouchDrag

Parametri

dragDirection: Enum.SwipeDirection
numberOfTouches: number
gameProcessedEvent: boolean

TouchEnded

L'evento TouchEnded si attiva quando un utente rilascia il dito dallo schermo di un DispositivoTouchEnabled, terminando l'input touch con il Dispositivo.

Questo evento può essere utilizzato per determinare quando un utente smette di toccare lo schermo del suo Dispositivo.Può essere abbinato a UserInputService.TouchStarted per determinare quando un utente inizia e smette di toccare lo schermo.

Ad esempio, il codice seguente stampa la posizione dello schermo in cui l'utente smette di toccare lo schermo.


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

L'oggetto di input touch è lo stesso oggetto di input durante tutta la vita del tocco.Quindi confrontare InputObjects quando sono oggetti touch è valido per determinare se è lo stesso dito.

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

Un'esempioInputObject che contiene informazioni sull'input dell'utente.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.

In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.

In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.

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

Sparato quando un utente tiene premuto almeno un dito per un breve periodo di tempo sullo stesso posizionamento dello schermo di un DispositivoTouchEnabled.

Questo evento può essere utilizzato per determinare quando un utente tiene premuto il dito su un elemento in gioco GuiObject o su un elemento.

L'esempio seguente stampa il state della pressa lunga quando l'utente tiene premuto almeno un dito per un breve periodo di tempo sullo stesso posizionamento dello schermo.Gli stati possibili includono: Inizia , Cambia , Fine , Annulla e Nessuno .


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)

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Può essere abbinato a UserInputService.TouchStarted e UserInputService.TouchEnded per determinare quando un utente inizia e smette di toccare lo schermo.

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

touchPositions: Array

Un array di Vector2 oggetti, che indica la posizione dei dita coinvolti nel gesto.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.

In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.

In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.

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

Si accende quando un utente muove il dito su un DispositivoTouchEnabled , come un tablet o uno smartphone.

Questo evento è utile per tracciare se un utente sta muovendo il dito sullo schermo, nonché dove l'utente sta muovendo il dito.

Il codice seguente mostra il tocco che si muove dalla sua posizione precedente a una nuova posizione su un DispositivoTouchEnabled .Nota che il InputObject.Position sul parametro passato touch è un Vector3 , ma include solo le coordinate X e Y; Z è sempre 0.


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)

Abina questo evento con UserInputService.TouchStarted e UserInputService.TouchEnded per determinare quando un utente inizia a toccare lo schermo, come si muove il dito mentre lo tocca e quando si ferma a toccare lo schermo.

Per controllare se il dispositivo di un utente supporta il tocco e che gli eventi di tocco si Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

Un'esempioInputObject che contiene informazioni sull'input dell'utente.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.

In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.

In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.

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

L'evento TouchPan si attiva quando un utente trascina almeno un dito su un DispositivoTouchEnabled .

Questo evento può essere utilizzato per determinare quando un utente fa scorrere il dito sullo schermo di un dispositivo TouchEnabled - ad esempio per ruotare il Camera in uno script della fotocamera personalizzata.

Il riquadro seguente stampa "Velocità del trascinamento del tocco" seguito dalla velocità del tocco dell'utente quando l'utente trascina il dito sullo schermo.


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

Dai un'occhiata ad un'altra utile funzione UserInputService qui UserInputService.TouchRotate .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

touchPositions: Array

Un array di Vector2 oggetti, che indica le posizioni dei tocchi (ad esempio le dita) coinvolti nel gesto.

totalTranslation: Vector2

La dimensione del gesto della padella dall'inizio alla fine (in pixel).

velocity: Vector2

La velocità del gesto della padella (in pixel) al secondo.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.

The script is broken into two parts:

  1. Mobile camera events, which rely on touch events
  2. Non-mobile camera events, which rely on keyboard input and tracking the user's movement

First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.

Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.

The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.

All of the parts discussed above are combined and shown in the code sample below.

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

Sparato quando un utente posiziona e muove due dita sullo schermo di un DispositivoTouchEnabled .

Ad esempio, il riquadro seguente mostra quanto la scala di zoom della fotocamera è cambiata dall'inizio della pinza touch.


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

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano.Ad esempio, gli input non verranno catturati quando la finestra è minimizzata.Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

touchPositions: Array

Un array di Vector2s , che indica la posizione dello schermo, in pixel, dei dita coinvolti nel gesto di pinzamento.

scale: number

La magnitudine del pinzamento da inizio a fine (in pixel) diviso dalle posizioni di pinzamento iniziali.

velocity: number

La velocità del gesto di pinza (in pixel) al secondo.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.

The script is broken into two parts:

  1. Mobile camera events, which rely on touch events
  2. Non-mobile camera events, which rely on keyboard input and tracking the user's movement

First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.

Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.

The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.

All of the parts discussed above are combined and shown in the code sample below.

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

L'evento TouchRotate si attiva quando un utente ruota due dita su un DispositivoTouchEnabled .

Ad esempio, il seguente codice stampa quanto la fotocamera si sia ruotata dall'inizio della rotazione touch.


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

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Gli script principali che controllano la fotocamera dell'utente su un dispositivo mobile utilizzano un codice che funziona in modo simile a questo evento.La migliore pratica per questo evento è utilizzarlo quando si crea un sistema di fotocamera mobile per sostituire gli script di base predefiniti.

Vedi anche:

Parametri

touchPositions: Array

Un array di Vector2s , che indica le posizioni dei dita coinvolti nel gesto.

rotation: number

Il numero di grado che il gesto ha ruotato dall'inizio del gesto.

velocity: number

Il cambiamento di rotazione (in gradi) diviso dalla durata del cambiamento (in secondi).

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.

The script is broken into two parts:

  1. Mobile camera events, which rely on touch events
  2. Non-mobile camera events, which rely on keyboard input and tracking the user's movement

First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.

Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.

The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.

All of the parts discussed above are combined and shown in the code sample below.

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

L'evento TouchStarted si attiva quando un utente posiziona il dito su un DispositivoTouchEnabled, iniziando l'input di tocco con il Dispositivo.

Questo evento può essere utilizzato per determinare quando un utente inizia a toccare lo schermo del suo Dispositivo.Può essere abbinato a UserInputService.TouchEnded per determinare quando un utente inizia e smette di toccare lo schermo.

L'oggetto di input touch è lo stesso oggetto di input durante tutta la vita del tocco.Quindi confrontare InputObjects quando sono oggetti touch è valido per determinare se è lo stesso dito.

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

Un'esempioInputObject che contiene informazioni sull'input dell'utente.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

This example demonstrates how to use touch input events to drag a GUI element while a player touches and drags across their screen.

The touch InputObject is the same input object throughout the lifetime of the touch. So comparing input objects when they are touch objects is valid to determine if it is the same touch as the input starts, changes, and ends.

The example starts tracking a drag once the touch is registered by the TouchStarted() event. It continues to update as that touch moves, tracking its position relative to start position to move a GUI until a TouchEvent event fires for that touch.

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

L'evento TouchSwipe si attiva quando un utente graffia le dita su un DispositivoTouchEnabled.

Questo evento può essere utilizzato per determinare quando un utente scorre le dita sullo schermo del suo dispositivo e la direzione che l'utente ha scorso.

Per una tracciabilità più precisa del movimento di input del tocco, usa UserInputService.TouchMoved

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

swipeDirection: Enum.SwipeDirection

Un Enum.SwipeDirection , che indica la direzione in cui l'utente ha scorso.

numberOfTouches: number

Numero di tocchi (ad esempio dita) coinvolti nel gesto.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The example below demonstrates the TouchSwipe() event by tweening a GuiObject|GUI element's position 100 pixels in the direction of the swipe according to the value of the swipeDirection argument.

In order for this example to work as expected, it must be placed in a LocalScript that is parented to the gui being swiped.

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

L'evento TouchTap si attiva quando l'utente tocca/tocca il dito sullo schermo su un DispositivoTouchEnabled .

Questo evento si attiverà indipendentemente dal fatto che l'utente tocchi/tocchi il mondo del gioco o un elemento GuiObject .Se stai cercando un evento che si attiva solo quando l'utente tocca/tocca il Mondodel gioco, usa UserInputService.TouchTapInWorld .

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Parametri

touchPositions: Array

Un array di Vector2 oggetti, che indica la posizione dei dita coinvolti nel gesto di tocco.

gameProcessedEvent: boolean

Indica se il motore di gioco ha osservato internamente questo input e ha agito su di esso.Generalmente questo si riferisce al trattamento dell'interfaccia utente, quindi se un pulsante è stato toccato o cliccato da questo input, gameProcessedEvent sarebbe true .Questo è anche vero per gli eventi di input connessi tramite ContextActionService .


Campioni di codice

The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.

In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.

In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.

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

L'evento TouchTapInWorld si attiva quando l'utente tocca/tocca il dito sullo schermo su un DispositivoTouchEnabled.Viene attivato quando l'utente tocca nel Mondodel gioco.

Questo evento può essere utilizzato per determinare quando un utente tocca lo schermo e non tocca un elemento GuiObject .Se l'utente tocca un elemento GUI, UserInputService.TouchTap verrà eseguito invece di TouchTapInWorld.

Per controllare se il dispositivo di un utente è TouchEnabled e che gli eventi di tocco verranno Lanciare, vedi UserInputService.TouchEnabled .

Questo evento si attiva solo quando la finestra del client Roblox è in primo piano. Ad esempio, gli input non verranno catturati quando la finestra viene minimizzata.

Poiché si attiva solo localmente, può essere utilizzato solo in un LocalScript .

Vedi anche:

Parametri

position: Vector2

Un Vector2 che indica la posizione del tocco.

processedByUI: boolean

Se l'utente ha toccato un elemento GUI.


Campioni di codice

This example uses the Vector2 position passed by TouchTapInWorld() to find the Vector3 world position the user tapped. Then, the code spawns an anchored BasePart|Part at the world position.

In order to calculate the Vector3 world position using the viewport position, this example generates a Ray called unitRay originating from position using the ViewportPointToRay() function. Then, since ViewportPointToRay() creates a unit ray that is only 1 stud long, the example uses it to create a longer ray that is length studs long. Using FindPartOnRay(), the code determines where the ray first intersects a part in the world - the Vector3 world position that the user tapped.

Note that the code sample will not spawn a part if the user touches on the screen over an empty skybox. The touch must be on a part for FindPartOnRay() to return a Vector3 position.

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

L'evento WindowFocusReleased si attiva quando la finestra del client Roblox perde il focus - tipicamente quando il client Roblox viene minimizzato dall'utente.

Ad esempio, il codice seguente stampa "Focalizzazione della finestra rilasciata" ogni volta che il client Roblox perde il focus.


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

Questo evento può essere utilizzato insieme a UserInputService.WindowFocused per tracciare se il client Roblox è attivamente focalizzato sullo schermo di un utente.

Poiché si attiva solo localmente, può essere utilizzato solo in un LocalScript .


Campioni di codice

This example fires a RemoveEvent to the server name AfkEvent when the LocalPlayer's client gains or loses focus.

The purpose of this code sample is to fire a server-side event to indicate when the player is AFK. This is indicated by spawning a ForceField around the player when the client loses focus and destroying the forcefield when the client gains focus.

In order for this example to work as expected, the code labelled LocalScript must be placed in a LocalScript and the code labelled Script must be placed in a Script. This sample is a Script which should be run in conjunction with the LocalScript code sample: Window Focus AFK Script (LocalScript)

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)

This sample is a LocalScript which should be run in conjunction with the Script code sample: Window Focus AFK Script (Script)

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

L'evento WindowFocused si attiva quando la finestra del client Roblox ottiene focus - tipicamente quando il client Roblox è massimizzato/aperto attivamente sullo schermo dell'utente.

Ad esempio, il codice seguente stampa "Finestra focalizzata" ogni volta che il client Roblox ottiene focus.


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

Questo evento può essere utilizzato insieme a UserInputService.WindowFocusReleased per tracciare se il client Roblox è attivamente focalizzato sullo schermo di un utente.

Poiché questo evento si attiva solo localmente, può essere utilizzato solo in un LocalScript .


Campioni di codice

This example fires a RemoveEvent to the server name AfkEvent when the LocalPlayer's client gains or loses focus.

The purpose of this code sample is to fire a server-side event to indicate when the player is AFK. This is indicated by spawning a ForceField around the player when the client loses focus and destroying the forcefield when the client gains focus.

In order for this example to work as expected, the code labelled LocalScript must be placed in a LocalScript and the code labelled Script must be placed in a Script. This sample is a Script which should be run in conjunction with the LocalScript code sample: Window Focus AFK Script (LocalScript)

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)

This sample is a LocalScript which should be run in conjunction with the Script code sample: Window Focus AFK Script (Script)

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)