UserInputService

Veraltete anzeigen

*Dieser Inhalt wurde mit KI (Beta) übersetzt und kann Fehler enthalten. Um diese Seite auf Englisch zu sehen, klicke hier.

Nicht erstellbar
Dienst
Nicht repliziert

UserInputService ist ein dienst, der verwendet wird, um die verschiedenen arten von eingängen zu erkennen und zu erfassen, die auf dem gerät eines benutzers verfügbar sind.

Der Hauptzweck dieses Dienstes besteht darin, Erlebnisse mit mehreren Formen der verfügbaren Eingabe zu kooperieren, wie z. B. Spielcontrollern, Touch-Bildschirmen und Tastaturen.Es ermöglicht ein LocalScript, verschiedene Aktionen auszuführen, abhängig vom Gerät, und bietet im Gegenzug das beste Erlebnis für den Endbenutzer.

Einige Verwendungen dieses Dienstes umfassen die Erkennung der Eingabe eines Benutzers, wenn er mit GUIs, Werkzeugen und anderen Spielinstanzen interagiert.Um die Eingabe eines Benutzers zu erkennen, muss der Service ein Service-Ereignis suchen.Zum Beispiel kann der Dienst Ereignisse wie erkennen, wenn der Benutzer die Bildschirm eines mobilen Geräts mit UserInputService.TouchStarted berührt oder einen Gamepad wie einen Xbox-Controller mit seinem Gerät verbindet, indem er UserInputService.GamepadConnected verwendet.

Da dieser Service nur clientseitig ist, wird er nur funktionieren, wenn er in einem LocalScript oder einem ModuleScript verwendet wird, das von einem LocalScript erforderlich ist.Da der UserInputService nur auf der Clientseite ist, können Benutzer im Spiel nur ihren eigenen Eingang erkennen - und nicht den Eingang anderer.

Siehe auch ContextActionService , einen Service, der es Ihnen ermöglicht, Funktionen an mehrere Benutzereingänge zu binden.

Code-Beispiele

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)

Zusammenfassung

Eigenschaften

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Beschreibt, ob das Gerät des Benutzers einen Beschleunigungsmesser hat.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Beschreibt, ob das Gerät, das von einem Benutzer verwendet wird, einen verfügbaren Gamepad hat.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Beschreibt, ob das Gerät des Benutzers ein Gyroskop hat.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Beschreibt, ob das Gerät des Benutzers eine Tastatur verfügbar hat.

  • Bestimmt, ob die Maus des Benutzers frei bewegt werden kann oder gesperrt ist.

  • Nicht repliziert
    Parallel lesen

    Skaliert die delta (Änderungs-) Ausgabe des Benutzers von Mouse.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Beschreibt, ob das Gerät des Benutzers eine Maus verfügbar hat.

  • MouseIcon:ContentId
    Parallel lesen

    Die Inhalts-ID des Bildes, das als Symbolverwendet wird.

  • Bestimmt, ob das Mouse-Symbol sichtbar ist.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Bestimmt die Position der Tastatur auf dem Bildschirm.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Bestimmt die Größe der Tastatur auf dem Bildschirm.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Beschreibt, ob eine Tastatur auf dem Bildschirm derzeit auf dem Bildschirm des Benutzers sichtbar ist.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Beschreibt, ob das aktuelle Gerät des Benutzers einen Touchscreen hat.

  • Schreibgeschützt
    Nicht repliziert
    Parallel lesen

    Weist darauf hin, ob der Benutzer einen Virtual-Reality-Headset verwendet.

Methoden

Ereignisse

Eigenschaften

AccelerometerEnabled

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob das Gerät des Benutzers ein Beschleunigungsmesser hat

Ein Beschleunigungsmesser ist ein Komponente, die in den meisten mobilen Geräten gefunden wird, die Beschleunigung misst (Geschwindigkeitsänderung).

Zum Beispiel zeigt das folgende Code-Snippet, wie man überprüft, ob das Gerät des Benutzers einen Beschleunigungsmesser hat.


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

Wenn das Gerät einen Beschleunigungsmesser aktiviert hat, können Sie seine aktuelle Beschleunigung erhalten, indem Sie die UserInputService:GetDeviceAcceleration()-Funktion verwenden oder verfolgen, wenn sich die Beschleunigung des Geräts durch die Verwendung des UserInputService.DeviceAccelerationChanged-Ereignisses ändert.

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Code-Beispiele

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

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob das Gerät, das von einem Benutzer verwendet wird, einen verfügbaren Gamepad hat.Wenn Spielpads verfügbar sind, kannst du UserInputService:GetConnectedGamepads() verwenden, um eine Liste von verbundenen Spielpads abzurufen.

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Siehe auch:

Code-Beispiele

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

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob das Gerät des Benutzers ein Gyroskop hat.

Ein Gyroskop ist ein Komponente, die in den meisten mobilen Geräten gefunden wird, die Orientierung und Drehgeschwindigkeit erkennen.

Wenn das Gerät eines Benutzers ein Gyroskop hat, kannst du es in deinem Spiel mit der Funktion UserInputService:GetDeviceRotation() und dem Ereignis UserInputService.DeviceRotationChanged verwenden.


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

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Code-Beispiele

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

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob das Gerät des Benutzers eine Tastatur verfügbar hat.Diese Eigenschaft ist true, wenn das Gerät des Benutzers eine verfügbare Tastatur hat, und false, wenn es nicht.

Es kann verwendet werden, um zu bestimmen, ob der Benutzer eine verfügbare Tastatur hat - was wichtig sein kann, wenn Sie überprüfen möchten, ob Sie UserInputService:IsKeyDown() oder UserInputService:GetKeysPressed() verwenden können, um nach Tastatureingabe zu suchen.

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Code-Beispiele

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

Parallel lesen

Diese Eigenschaft legt fest, wie sich die Maus des Benutzers verhält, basierend auf der Enum.MouseBehavior Enum. Sie kann auf drei Werte festgelegt werden:

Der Wert dieser Eigenschaft hat keinen Einfluss auf die Empfindlichkeit der Verfolgung der Mausbewegung bei der Ereignisverfolgung.Zum Beispiel gibt GetMouseDelta die gleiche Vector2 Bildschirmposition in Pixeln zurück, unabhängig davon, ob die Maus gesperrt ist oder sich frei um den Bildschirm des Benutzers bewegen kann.Als Ergebnis sind Standard-Skripte wie diejenigen, die die Kamera steuern, durch diese Eigenschaftennicht betroffen.

Diese Eigenschaft wird überschrieben, wenn ein mit aktiviert ist, es sei denn, die rechte Maustaste des Spieler:inist unten.

Beachten Sie, dass, wenn die Maus gesperrt ist, UserInputService.InputChanged immer noch feuert, wenn der Spieler die Maus bewegt und die Delta passiert, die die Maus versucht hat, sich zu bewegen.Zusätzlich, wenn der Spieler aus dem Spiel geworfen wird, wird die Maus zwangsweise freigeschaltet.

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Code-Beispiele

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

Nicht repliziert
Parallel lesen

Diese Eigenschaft legt die Empfindlichkeit des Mouse des Benutzers fest.

Die Empfindlichkeit legt fest, inwieweit eine Bewegung der physischen Maus sich auf eine Bewegung der Maus im Spiel überträgt.Dies kann verwendet werden, um angepasst zu werden, wie sensible Ereignisse, die die Bewegung der Maus verfolgen, wie GetMouseDelta, mit der Mausbewegung korrelieren.

Diese Eigenschaft wirkt sich nicht auf die Bewegung des Symbolaus.Es wirkt sich auch nicht auf die Kameraempfindlichkeit-Einstellung aus, die im Einstellungen-Tab des Menüs der Einstellungen des Clients gefunden wird, die auch die Empfindlichkeit der Ereignisverfolgungsmaus beeinflusst.

Diese Eigenschaft hat einen maximalen Wert von 10 und einen minimalen Wert von 0.Ein niedriger Wert entspricht niedriger Empfindlichkeit und ein höherer Wert höherer Empfindlichkeit.

Wenn die Empfindlichkeit 0 ist, feuern Ereignisse, die die Bewegung der Maus verfolgen, immer noch ab, aber alle Parameter und Eigenschaften, die die Änderung der Mausposition anzeigen, geben Vector2.new() oder Vector3.new() im Falle von InputObject.Delta zurück.Zum Beispiel wird GetMouseDelta immer zurückkehren (0, 0).

Code-Beispiele

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

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob das Gerät des Benutzers eine verfügbare Maus hat.Diese Eigenschaft ist true, wenn das Gerät des Benutzers eine verfügbare Maus hat, und false, wenn es keine hat.


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

Es ist wichtig, dies zu überprüfen, bevor du UserInputService Mausfunktionen wie UserInputService:GetMouseLocation() verwendest.

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Siehe auch:

Code-Beispiele

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
Parallel lesen

Die Eigenschaft MouseIcon bestimmt das Bild, das als Zeiger verwendet wird.Wenn leer, wird ein Standardpfeil verwendet.Während der Cursor über bestimmte UI-Objekte wie ein ImageButton, TextButton, TextBox oder ProximityPrompt schwebt, wird dieses Bild überschrieben und vorübergehend ignoriert.

Um den Cursor vollständig auszublenden, tun Sie nicht verwenden ein transparentes Bild. Stattdessen setzen Sie UserInputService.MouseIconEnabled auf false.

Code-Beispiele

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

Parallel lesen

Diese Eigenschaft bestimmt, ob das Mouse -Symbol sichtbar ist, wenn das true -Symbol der Maus sichtbar ist, wenn false es nicht ist.

Zum Beispiel versteckt das Code-Snippet unten das Symbol der Maus.


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

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Code-Beispiele

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

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt die Position der Tastatur auf dem Bildschirm in Pixeln. Die Tastaturposition ist Vector2.new(0, 0), wenn sie nicht sichtbar ist.

Da nur clientseitig ist, kann diese Eigenschaft nur in einem oder einem mit verwendet werden, um auf festgelegt zu werden.

Siehe auch OnScreenKeyboardVisible und OnScreenKeyboardSize.

Code-Beispiele

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

UserInputService.OnScreenKeyboardPosition

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

OnScreenKeyboardSize

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt die Größe der Tastatur auf dem Bildschirm in Pixeln. Die Größe der Tastatur ist Vector2.new(0, 0), wenn sie nicht sichtbar ist.

Da nur clientseitig ist, kann diese Eigenschaft nur in einem oder einem mit verwendet werden, um auf festgelegt zu werden.

Siehe auch OnScreenKeyboardVisible und OnScreenKeyboardPosition.

OnScreenKeyboardVisible

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob eine Tastatur auf dem Bildschirm derzeit auf dem Bildschirm des Benutzers sichtbar ist.

Da nur clientseitig ist, kann diese Eigenschaft nur in einem oder einem mit verwendet werden, um auf festgelegt zu werden.

Siehe auch OnScreenKeyboardSize und OnScreenKeyboardPosition.

TouchEnabled

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob das aktuelle Gerät des Benutzers einen Touchscreen verfügbar hat.

Die Eigenschaft wird verwendet, um zu bestimmen, ob das Gerät des Benutzers einen Touchscreen hat, und daher ob Touch-Ereignisse initiierenwerden.Wenn TouchEnabled wahr ist, können Sie Benutzeingabedienste-Ereignisse wie UserInputService.TouchStarted und UserInputService.TouchEnded verwenden, um zu verfolgen, wann ein Benutzer beginnt und aufhört, den Bildschirm ihres Geräts zu berühren.

Das Code-Snippet unten druckt aus, ob das Gerät des Benutzers einen Touchscreen hat.


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

Siehe auch:

Code-Beispiele

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

Schreibgeschützt
Nicht repliziert
Parallel lesen

Diese Eigenschaft beschreibt, ob der Benutzer ein virtuelles Gerät(VR) verwendet.

Wenn ein VR-Gerät aktiviert ist, kannst du mit seiner Position und Bewegung durch Funktionen wie UserInputService:GetUserCFrame() interagieren.Du kannst auch auf die Bewegung des VR-Geräts mit dem UserInputService.UserCFrameChanged-Ereignis reagieren.


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

Da UserInputService nur auf clientseitig ist, kann diese Eigenschaft nur in einem LocalScript verwendet werden.

Siehe auch:

Code-Beispiele

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

Methoden

GamepadSupports

Diese Funktion gibt zurück, ob das angegebene Enum.UserInputType Spielpad einen Knopf unterstützt, der dem angegebenen Enum.KeyCode entspricht.Diese Funktion wird verwendet, um gültige Gamepad-Eingaben zu bestimmen.

Um zu bestimmen, welche Enum.UserInputType Spielgeräte verbunden sind, verwende UserInputService:GetConnectedGamepads().

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadNum: Enum.UserInputType

Die Enum.UserInputType des Gamepads.

Standardwert: ""
gamepadKeyCode: Enum.KeyCode

Die Enum.KeyCode des Buttons in Frage.

Standardwert: ""

Rückgaben

Ob das angegebene Gamepad einen Button unterstützt, der dem angegebenen Enum.KeyCode entspricht.

Code-Beispiele

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

Diese Funktion gibt eine Liste von Enum.UserInputType Spielen zurück, die derzeit verbunden sind.Wenn keine Gamepads verbunden sind, wird diese Liste leer sein.Zusätzlich gibt es nur UserInputType-Objekte zurück, die Gamepads sind.Zum Instanzwird dieses Ereignis ein verbundenes Gamepad1-Objekt zurückgeben, aber kein Tastatur-Objekt.

Zum Beispiel ruft das folgende Code-Snippet die verbundenen Gamepads ab und speichert sie in einer Variable mit dem Namen verbundene Gamepads.


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

Um zu überprüfen, ob ein bestimmtes Gamepad verbunden ist, verwende UserInputService:GetGamepadConnected().

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:


Rückgaben

Ein Array von UserInputTypes, das den mit dem Gerät des Benutzers verbundenen Gamepads entspricht.

Code-Beispiele

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

Die Funktion GetDeviceAcceleration bestimmt die aktuelle Beschleunigung des Geräts des Benutzers.Es gibt eine InputObject zurück, die die aktuelle Beschleunigung des Geräts beschreibt.

Damit dies funktioniert, muss das Gerät des Benutzers einen aktivierten Beschleunigungsmesser haben.Um zu überprüfen, ob das Gerät eines Benutzers einen Beschleunigungsmesser hat, kannst du die EigenschaftenUserInputService.AccelerometerEnabled überprüfen.

Wenn du stattdessen verfolgen möchtest, wann sich die Beschleunigung des Geräts des Benutzers ändert, kannst du das Ereignis UserInputService.DeviceAccelerationChanged verwenden.

Da es nur lokal feuert, kann es nur in einem LocalScript verwendet werden.


Rückgaben

Code-Beispiele

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

Diese Funktion gibt einen InputObject zurück, der den aktuellen Vektorkraftdes Geräts beschreibt.

Der Gravitationsvektor wird durch die Orientierung des Geräts in Bezug auf die Gravitationskraft der realen Welt bestimmt.Wenn ein Gerät zum Instanzperfekt waagerecht (Hochformat) ist, ist der Schwerkraftvektor Vector3.new(0, 0, -9.18) .Wenn die linke Seite des Geräts nach unten zeigt, ist der Vektor Vector3.new(9.81, 0, 0).Schließlich, wenn die Rückseite des Geräts nach unten zeigt, ist der Vektor Vector3.new(0, -9.81, 0).

Diese Funktion kann verwendet werden, um das Gerät des Benutzers zu aktivieren, die Gravitation innerhalb des Spiels zu beeinflussen oder In-Game-Objekte wie einen Ball zu bewegen.

Schwerkraft wird nur für Spieler verfolgt, die ein Gerät mit einem aktivierten Gyroskop verwenden - wie ein mobiles Gerät.

Um zu überprüfen, ob das Gerät eines Benutzers ein Gyroskop hat, überprüfe den Wert von UserInputService.GyroscopeEnabled.Wenn das Gerät ein Gyroskop aktiviert hat, kannst du auch das Ereignis UserInputService.DeviceGravityChanged verwenden, um zu verfolgen, wann sich die Schwerkraft auf dem Gerät des Benutzers ändert.

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.


Rückgaben

Code-Beispiele

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

Diese Funktion gibt eine InputObject und eine CFrame zurück, die den aktuellen Vektorkraftdes Geräts beschreiben.

Dies wird mit einem InputObject abgefeuert.Die Position-Eigenschaft des Eingabeelements ist eine Enum.InputType.Gyroscope, die die gesamte Rotation in jedem lokalen Gerät轴 verfolgt.

Die Geräte rotation kann nur auf Geräten mit einem gyroscope verfolgt werden.

Da diese Funktion lokal feuert, kann sie nur in einem LocalScript verwendet werden.


Rückgaben

Eine Tupla mit zwei Eigenschaften:

  1. Die Delta-Eigenschaft beschreibt die Menge der Rotation, die zuletzt passiert ist
  2. Der CFrame ist die aktuelle Rotation des Geräts im Vergleich zu seinem Standardreferenzrahmen.

Code-Beispiele

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

Diese Funktion gibt die TextBox zurück, auf die sich der Client derzeit konzentriert.Ein TextBox kann vom Benutzer manuell ausgewählt werden, oder die Auswahl kann mit der Funktion TextBox:CaptureFocus() erzwungen werden.Wenn keine TextBox ausgewählt ist, gibt diese Funktion nil zurück.

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch

Rückgaben

GetGamepadConnected

Diese Funktion gibt zurück, ob ein Gamepad mit der angegebenen Enum.UserInputType Verbindung zum Client verbunden ist.

Dies kann verwendet werden, um zu überprüfen, ob ein bestimmtes Gamepad, wie 'Gamepad1', mit dem Gerät des Clients verbunden ist.

Um eine Liste aller verbundenen Gamepads abzurufen, verwende UserInputService:GetConnectedGamepads().

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadNum: Enum.UserInputType

Das Enum.UserInputType des Spielgeräts in Frage.

Standardwert: ""

Rückgaben

Ob ein Gamepad, das mit Enum.UserInputType verbunden ist, verbunden ist.

Code-Beispiele

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

Diese Funktion gibt eine Matrix von InputObjects für alle verfügbaren Eingänge auf dem angegebenen Enum.UserInputType Gamepadzurück, die den letzten Eingabezustand jedes Eingangs darstellt

Um die UserInputTypes der verbundenen Spielkonsolen zu finden, verwende UserInputService:GetConnectedGamepads().

Da diese Funktion nur lokal feuert, kann sie nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadNum: Enum.UserInputType

Die Enum.UserInputType entspricht dem Gamepad, das in Frage kommt.

Standardwert: ""

Rückgaben

Ein Array von InputObjects, das den aktuellen Zustand aller verfügbaren Eingänge für das angegebene Gamepad darstellt.

GetImageForKeyCode

ContentId

Diese Methode nimmt das angeforderte Enum.KeyCode und gibt das dazugehörige Bild für das aktuell verbundene Spielpadgerät (begrenzt auf Xbox, PlayStation und Windows) zurück.Das bedeutet, dass, wenn der verbundene Controller ein Xbox-One-Controller ist, der Benutzer Xbox-Assets sieht.Ebenso, wenn das verbundene Gerät ein PlayStation-Controller ist, sieht der Benutzer PlayStation-Assets.Wenn du benutzerdefinierte Assets verwenden möchtest, siehe GetStringForKeyCode().

Parameter

keyCode: Enum.KeyCode

Die Enum.KeyCode für die das zugeordnete Bild abgerufen werden soll.

Standardwert: ""

Rückgaben

ContentId

Die zurückgegebene Bild-Asset-ID.

Code-Beispiele

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

Diese Funktion gibt eine Matrix von InputObjects zurück, die mit den derzeit gedrückten Tasten verbunden ist.

Dieses Array kann durchlaufen werden, um zu bestimmen, welche Tasten derzeit gedrückt werden, mithilfe der InputObject.KeyCode Werte.

Um zu überprüfen, ob eine bestimmte Taste gedrückt wird, verwende UserInputService:IsKeyDown().

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.


Rückgaben

Ein Array von InputObjects, das mit den derzeit gedrückten Tasten verbunden ist.

Code-Beispiele

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

Diese Funktion gibt 'Enum.UserInputType' zurück, das mit dem jüngsten Eingabeeingabe des Benutzers verbunden ist.

Wenn zum Beispiel die frühere Eingabe des Benutzers die Leertaste gedrückt hatte, wäre die zurückgegebene Enum.UserInputType'Tastatur' .

Das Ereignis UserInputService.LastInputTypeChanged kann verwendet werden, um zu verfolgen, wann das letzte Enum.UserInputType vom Benutzer verwendet wurde, das sich geändert hat.

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.


Rückgaben

Die Enum.UserInputType mit dem jüngsten Eingabeeingang des Benutzers verbunden ist.

Code-Beispiele

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

Diese Funktion gibt eine Matrix von InputObjects zurück, die den aktuell gedrückten Mausknöpfen entspricht.

Mausknöpfe, die von dieser Funktion verfolgt werden, umfassen:


<td>Beschreibung</td>
</tr>
</thead>
<tr>
<td>Mausknopf1</td>
<td>Die linke Maus-Taste.</td>
</tr>
<tr>
<td>Maus-Button2</td>
<td>Die rechte Maustaste.</td>
</tr>
<tr>
<td>Maus-Button3</td>
<td>Die mittlere Maustaste.</td>
</tr>
Namen

Wenn der Benutzer keine Maus-Taste gedrückt hat, wenn die Funktion aufgerufen wird, gibt sie eine leere Arrayzurück.

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.


Rückgaben

Ein Array von InputObjects, das den aktuell gehaltenen Mausknöpfen entspricht, die derzeit gedrückt werden.

Code-Beispiele

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

Diese Funktion gibt die Änderung, in Pixeln, der Position des Spieler:inMouse im letzten gerenderten Frame als Vector2 zurück.Diese Funktion funktioniert nur, wenn die Maus mit der EigenschaftenUserInputService.MouseBehavior gesperrt wurde.Wenn die Maus nicht gesperrt wurde, sind die zurückgegebenen Vector2 Werte null.

Die Empfindlichkeit der Maus, die in den Einstellungen des Clients festgelegt ist und UserInputService.MouseDeltaSensitivity , wird das Ergebnis beeinflussen.

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.


Rückgaben

Änderung der Bewegung der Maus.

Code-Beispiele

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

Diese Funktion gibt eine Vector2 zurück, die die aktuelle Bildschirmposition des Spieler:inMouse in Pixeln im oberen linken Eck darstellt.Dies berücksichtigt nicht die Enum.ScreenInsets ; um die oberen und unteren Einfügungen links und rechts zu erhalten, rufen Sie GuiService:GetGuiInset() an.

Wenn die Position des Mauszeigers außerhalb des Bildes ist oder das Gerät des Spieler:inkeine Maus hat, wird der zurückgegebene Wert unbestimmt sein.

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.


Rückgaben

Ein Vector2 repräsentiert die aktuelle Bildschirmposition der Maus, in Pixeln.

Code-Beispiele

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

Diese Funktion gibt eine Reihe von Gamepad UserInputTypes zurück, die verbunden und für die GUI-Navigation aktiviert sind.Diese Liste ist in absteigender Priorität, was bedeutet, dass sie durchlaufen werden kann, um zu bestimmen, welches Gamepad die Navigationssteuer haben soll.

Ob ein verbundenes Gamepad ein Navigations-Gamepad ist, bestimmt nur, welche Gamepads die Navigations-GUIs steuern.Dies wirkt sich nicht auf Steuerungaus.

Da UserInputService nur clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:


Rückgaben

Ein Array von UserInputTypes, das für die GUI-Navigation verwendet werden kann, in absteigender Priorität.

GetStringForKeyCode

GetStringForKeyCode gibt eine Zeichenkette zurück, die ein Schlüssel ist, den der Benutzer drücken soll, um einen bestimmten Enum.KeyCode einzugeben, unter Berücksichtigung seiner Tastatur布置.Für Schlüsselcodes, die einen Modifikator erfordern, der gehalten werden muss, gibt diese Funktion den Schlüssel zurück, der zusätzlich zum Modifikator gedrückt werden muss.Siehe die Beispiele unten für weitere Erklärung.

Wenn du Roblox mit einer nicht-QWERTY-Tastaturlegende verwendest, werden Tastencode-Kodierungen auf gleichwertige QWERTY-Positionen gemappt.Zum Beispiel, wenn Sie auf einer AZERTY-Tastatur A drücken, ergibt sich Enum.KeyCode.Q.Diese Mapping kann zu unpassenden Informationen auf Erfahrungs-UI-Elementen führen.Zum Beispiel, "Drücken Sie M, um die Karte zu öffnen", ist auf einer AZERTY-Tastatur ungenau; es müsste "Drücken Sie ?, um die Karte zu öffnen", sein, was in derselben Position wie M auf QWERTY ist.Diese Funktion löst dieses Problem, indem sie den tatsächlichen Taste drückt, während du nicht-QWERTY-Tastaturlayouts verwendest.


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

<th>Wert zurückgeben</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.Äquivalent</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>2</code> weil <code>@</code> mit <kbd>Shift</kbd><kbd>2</kbd> getippt wird</td>
</tr>
</tbody>
Kenncode
Beispiele auf AZERTY-Tastatur

<th>Wert zurückgeben</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.Äquivalent</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>É</code></td>
</tr>
</tbody>
Kenncode
Gamepad-Verwendung

GetStringForKeyCode() gibt die String-Karte für das Enum.KeyCode für das zuletzt verbundene Gamepadzurück.Wenn der verbundene Controller nicht unterstützt wird, gibt die Funktion die Standardtextkonvertierung für den angeforderten Codeszurück.

Das folgende Beispiel zeigt, wie du benutzerdefinierte Assets für ButtonA mappen kannst:


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

Die Richtungspad-Tastenkodierungen haben keine Unterschiede basierend auf dem Gerät.Enum.KeyCode.ButtonSelect hat in einigen Fällen ein etwas anderes Verhalten.Verwende beide PlayStation-Mappings, um sicherzustellen, dass Benutzer die richtigen Schaltflächen sehen.


<th>PlayStation-Rückgabewert</th>
<th>Xbox-Rückgabewert</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.ButtonA</code></td>
<td><code>KnopfCross</code></td>
<td><code>SchaltflächeA</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonB</code></td>
<td><code>Knopfkreis</code></td>
<td><code>SchaltflächeB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td><code>KnopfSquare</code></td>
<td><code>SchaltflächeX</code></td>
</tr>
<tr>
<td><code>Enumer.KeyCode.ButtonY</code></td>
<td><code>Knopf dreieck</code></td>
<td><code>KnopfY</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL1</code></td>
<td><code>Schaltfläche L1</code></td>
<td><code>KnopfLB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL2</code></td>
<td><code>SchaltflächeL2</code></td>
<td><code>SchaltflächeLT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL3</code></td>
<td><code>SchaltflächeL3</code></td>
<td><code>ButtonLS</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR1</code></td>
<td><code>Schaltfläche R1</code></td>
<td><code>SchaltflächeRB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR2</code></td>
<td><code>Schaltfläche R2</code></td>
<td><code>SchaltflächeRT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR3</code></td>
<td><code>Schaltfläche R3</code></td>
<td><code>SchaltflächeRS</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonStart</code></td>
<td><code>Knopfoptionen</code></td>
<td><code>Taste starten</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonSelect</code></td>
<td><code>ButtonTouchpad</code> und <code>ButtonShare</code></td>
<td><code>Knopfauswählen</code></td>
</tr>
</tbody>
Kenncode
Systembilder für Schlüsselcodes

Wenn Sie ein Enum.KeyCode verwenden, das besser als Bild dargestellt werden kann, z. B. für ein ImageLabel in einer Benutzeroberfläche, können Sie die folgenden Legacy-Ikonen verwenden.Es wird jedoch empfohlen, GetImageForKeyCode() als moderne, crossplattformübergreifende Methode zu verwenden, um Xbox- und PlayStation-Controller-Icons abzurufen.


<th>Bild</th>
<th>Asset-ID</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/Kontrollen/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/Kontrollen/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/Controls/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/Controls/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/Controls/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/Controls/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/Controls/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/Kontrollen/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/Kontrollen/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/Kontrollen/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/Controls/return.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Linksschaltfläche</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.Rechtsverschiebung</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/Controls/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/Controls/comma.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Zitieren</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>
Kenncode

Parameter

keyCode: Enum.KeyCode
Standardwert: ""

Rückgaben

GetSupportedGamepadKeyCodes

Diese Funktion gibt eine Liste von KeyCodes, die der Gamepad, der mit dem angegebenen Enum.UserInputType verbunden ist, unterstützt, zurück.

Diese Funktion kann verwendet werden, um zu bestimmen, welche Tastaturschaltflächen von einem verbundenen Gamepad unterstützt und nicht unterstützt werden.Um festzustellen, ob ein bestimmter Schlüsselcode unterstützt wird, verwende UserInputService:GamepadSupports().

Wenn auf einem nicht existierenden oder nicht verbundenen Gamepad aufgerufen wird, gibt diese Funktion eine leere Arrayzurück.

Da UserInputService nur auf clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadNum: Enum.UserInputType

Die Enum.UserInputType des Gamepads.

Standardwert: ""

Rückgaben

Ein Array von KeyCodes, das vom angegebenen Gamepad unterstützt wird.

Code-Beispiele

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

Diese Funktion prüft, ob ein bestimmter Button auf einem bestimmten Gamepad gedrückt wird.Es gibt true zurück, wenn das gamepad die angegebene button gedrückt hat, sonst gibt es false zurück.

Gültige Benutereingabetypen

Das angegebene Gamepad sollte einer der folgenden UserInputType-Enum-Werte sein:


<tr>
<td>Enum.UserInputType.Gamepad1-8</td>
</tr>
Namen
Gültige Tastaturlayouts

Die angegebene Schaltfläche sollte einer der folgenden KeyCodes-Enum-Werte sein:


<tr>
<td>Enum.KeyCode.ButtonX</td>
</tr>
<tr>
<td>Enumer.KeyCode.ButtonY</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonA</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonB</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR1</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonL1</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR2</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonL2</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR3</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonL3</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonStart</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonSelect</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadLink</td>
</tr>
<tr>
<td>Enumer.KeyCode.DPadRight</td>
</tr>
<tr>
<td>Enumer.KeyCode.DPadUp</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadDown</td>
</tr>
Namen

Dies kann verwendet werden, um zu überprüfen, ob eine bestimmte Taste, wie A, gedrückt gehalten wird. Zum Beispiel:


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

Da UserInputService nur clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadNum: Enum.UserInputType

Die Enum.UserInputType des angegebenen Gamepads.

Standardwert: ""
gamepadKeyCode: Enum.KeyCode

Die Enum.KeyCode des angegebenen Buttons.

Standardwert: ""

Rückgaben

Ob die angegebene Gamepad-Taste auf dem angegebenen Gamepad gedrückt wird, wird gedrückt.

Code-Beispiele

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

Diese Funktion gibt zurück, ob der Benutzer die Taste gedrückt hält, die mit dem angegebenen Enum.KeyCode verbunden ist.Es gibt zurück true wenn der angegebene Schlüssel gedrückt wird oder false wenn er nicht gedrückt wird.

Dies kann verwendet werden, um zu überprüfen, ob eine bestimmte Schlüssel, wie die Leertaste, gedrückt wird. Zum Beispiel:


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

Um eine Liste aller von der Benutzerin gedrückten Tasten abzurufen, verwende die UserInputService:GetKeysPressed()-Funktion.

Da UserInputService nur clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

keyCode: Enum.KeyCode

Die Enum.KeyCode des Schlüssels.

Standardwert: ""

Rückgaben

Ob der angegebene Schlüssel gedrückt wird.

Code-Beispiele

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

Diese Funktion nimmt eine Maus-Taste Enum.UserInputType und gibt einen bool zurück, der anzeigt, ob sie derzeit gedrückt wird.

Die überprüfte Maus-Taste hängt vom Enum.UserInputType Wert ab, der an die Funktion als Argument übergeben wurde. Zum Beispiel:


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

Da UserInputService nur clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden."

Parameter

mouseButton: Enum.UserInputType

Die Enum.UserInputType des Mausknopfes.

Standardwert: ""

Rückgaben

Ob der angegebene Mausknopf derzeit gedrückt gehalten wird.

Code-Beispiele

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

Diese Funktion gibt true zurück, wenn das angegebene Enum.UserInputType Spielpad die Navigation und Auswahl GuiObjects steuern darf.

Wenn du ein Navigations-Gamepad einrichten möchtest, kannst du UserInputService:SetNavigationGamepad() verwenden. Du kannst auch UserInputService:GetNavigationGamepads() verwenden, um eine Liste aller Navigations-Gamepads zu erhalten.

Zum Beispiel prüft der Code unten, ob das Gamepad1 als Navigationsgamepad ist:


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

Eine Liste aller verbundenen Gamepads, unabhängig von der Navigation, kann mit `UserInput/GetConnectedGamepads abgerufen werden.

Da UserInputService nur clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadEnum: Enum.UserInputType

Die Enum.UserInputType des angegebenen Gamepads.

Standardwert: ""

Rückgaben

Ob das angegebene Gamepad ein Navigations-Gamepad ist.

RecenterUserHeadCFrame

()

Diese Funktion richtet das CFrame des VR-Headsets auf die aktuelle Orientierung des Headsets aus, das vom Benutzer getragen wird.Das bedeutet, dass die aktuelle Orientierung des Headsets auf CFrame.new() festgelegt ist.

Verwende diese Funktion, um das Kopfhörer-CFRame in die Mitte des Spielbereichs zu verschieben, wenn es an einem seltsamen Versatz scheint.

Dies verhält sich identisch zur VRService Funktion, VRService:RecenterUserHeadCFrame().

Da UserInputService nur clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.


Rückgaben

()

Code-Beispiele

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

()

Die Funktion SetNavigationGamepad legt fest, ob das angegebene Enum.UserInputType Spielpad den GUI-Navigator bewegen kann.Ein Gamepad, das es erlaubt, den GUI-Navigator zu bewegen, gilt als Navigations-Gamepad.

Wenn das aktivierte Argument als true, kann das Gamepad den GUI-Navigator bewegen.Wenn das Argument false ist, kann das Gamepad den GUI-Navigator nicht bewegen.

Wenn du überprüfen möchtest, ob ein bestimmtes Gamepad ein festgelegtes Navigations-Gamepad ist, kannst du die UserInputService:IsNavigationGamepad()-Funktion verwenden.Du kannst auch die UserInputService:GetNavigationGamepads() verwenden, um eine Liste aller Navigationsgamepads abzurufen.

Da UserInputService nur clientseitig ist, kann diese Funktion nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadEnum: Enum.UserInputType

Die Enum.UserInputType des angegebenen Gamepads.

Standardwert: ""
enabled: boolean

Ob das angegebene Gamepad den GUI-Navigator bewegen kann.

Standardwert: ""

Rückgaben

()

Code-Beispiele

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)

Ereignisse

DeviceAccelerationChanged

Das Ereignis "DeviceAccelerationChanged" wird ausgelöst, wenn ein Benutzer ein Gerät bewegt, das einen Beschleunigungsmesser hat.

Ein Beschleunigungsmesser ist ein Komponente, die in den meisten mobilen Geräten gefunden wird, die Beschleunigung misst (Geschwindigkeitsänderung).

Um zu bestimmen, ob das Gerät eines Benutzers einen Beschleunigungsmesser aktiviert hat, siehe UserInputService.AccelerometerEnabled .

Dieses Ereignis kann verwendet werden, um die Bewegung eines Geräts zu verfolgen, das einen Beschleunigungsmesser hat.Eine Beispielnutzung beinhaltet das Bewegen des Spielcharakters, wenn ein mobiles Gerät beschleunigt wird.

Zusätzlich kann dieses Ereignis zusammen mit UserInputService:GetDeviceAcceleration() verwendet werden, um die aktuelle Bewegung eines Geräts eines Benutzers zu bestimmen, wenn das Gerät einen Beschleunigungsmesser hat.

Dieses Ereignis wird nur lokal ausgelöst - was bedeutet, dass nur der Spieler, dessen Gerät sich bewegt, das Ereignis verwenden kann, und es wird nur in einem LocalScript funktionieren.

Parameter

acceleration: InputObject

Ein InputObject , mit einem UserInputType von 'Accelerometer' und Position , das die Kraft der Gravitation auf jedem lokalen Gerätachse zeigt.


Code-Beispiele

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

Das Ereignis UserInputService.DeviceGravityChanged wird ausgelöst, wenn sich die Gravitation des Geräts Vector3 auf einem Gerät, das einen Beschleunigungsmesser hat, ändert.

Der Schwerkraftvektor eines Geräts repräsentiert die Schwerkraft auf jedem der X-, Y- und Z-Achsen des Geräts.Während die Gravitation sich nie ändert, ändert sich die Kraft, die sie auf jede Achse ausübt, wenn das Gerät rotiert und die Orientierung ändert.Der Kraftwert, der auf jede Achse ausgeübt wird, ist ein Einheitenvektor, der von -1 bis 1 reicht.

Ein Beschleunigungsmesser ist ein Komponente, die in den meisten mobilen Geräten gefunden wird, die Beschleunigung misst (Geschwindigkeitsänderung).

Dieses Ereignis kann verwendet werden, um die Richtung der Gravitationskraft in der realen Welt auf dem Gerät eines Benutzers zu bestimmen.Dies kann dann sogar verwendet werden, um die Kraft der Gravitation auf dem Gerät eines Benutzers innerhalb des Spiels zu simulieren, wie auf In-Game-Objekten (siehe Beispiel unten).

Um zu überprüfen, ob das Gerät eines Benutzers einen Beschleunigungsmesser hat, siehe UserInputService.AccelerometerEnabled .Wenn das Gerät einen aktivierten Beschleunigungsmesser hat, kannst du die UserInputService:GetDeviceGravity()-Funktion verwenden, um die aktuelle Gravitationskraft auf dem Gerät des Benutzers zu erhalten.

Parameter

gravity: InputObject

Ein InputObject, mit einer InputObject.Position Eigenschaft, die die Kraft der Gravitation auf jedem lokalen Gerätachse zeigt.Diese Position kann als Richtung verwendet werden, um die Richtung der Gravitation in Bezug auf das Gerät zu bestimmen.


Code-Beispiele

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

Das Ereignis "Geräte rotation geändert" wird ausgelöst, wenn ein Benutzer ein Gerät dreht, das ein Gyroskop hat.

Ein Gyroskop ist ein Komponente, die in den meisten mobilen Geräten gefunden wird, die Orientierung und Drehgeschwindigkeit erkennen.

Das Ereignis ist nützlich, wenn Sie die Orientierung des Geräts verfolgen und die Änderungen verfolgen, wenn der Benutzer sein Gerät dreht.Um die aktuelle Geräte rotation zu bestimmen, kannst du die UserInputService:GetDeviceRotation() Funktion verwenden.

Um zu überprüfen, ob das Gerät eines Benutzers ein Gyroskop hat, und dass dieses Ereignis initiierenwird, siehe UserInputService.GyroscopeEnabled.

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Parameter

rotation: InputObject

Ein InputObject, der Informationen über die Rotation des Geräts liefert. InputObject.Position repräsentiert die neue Rotation einen Vector3 positionalen Wert und InputObject.Delta repräsentiert die Änderung der Rotation in einem Vector3 positionalen Wert.

cframe: CFrame

Ein CFrame repräsentiert die aktuelle Orientierung des Geräts.


Code-Beispiele

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

Das GamepadConnected-Ereignis wird ausgelöst, wenn ein Gamepad mit dem Client verbunden wird.

Da ein Roblox-Spiel mehrere Controller unterstützt, ist dieses Ereignis nützlich, wenn es mit dem Ereignis UserInputService.GamepadDisconnected verbunden wird, um zu verfolgen, welche Controller/Gamepads aktiv sind.Du kannst auch UserInputService:GetConnectedGamepads() verwenden, um den richtigen Gamepad zu finden, um zu verwenden.

Das folgende Beispiel zeigt ein Nutzungsbeispiel für ein Tracking, wenn ein Gamepad mit dem Client verbunden ist.


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

Wenn du sehen möchtest, welche Geräte verbunden sind, kannst du die UserInputService:GetConnectedGamepads()-Funktion verwenden.

Da dieses Ereignis lokal ausgelöst wird, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadNum: Enum.UserInputType

Das Enum.UserInputType des verbundenen Gamepads.


GamepadDisconnected

Das GamepadDisconnected-Ereignis wird ausgelöst, wenn ein Gamepad getrennt wird.

Da ein Roblox-Spiel mehrere Controller unterstützt, ist dieses Ereignis nützlich, wenn es mit dem Ereignis UserInputService.GamepadConnected verbunden wird, um zu verfolgen, welche Controller/Gamepads aktiv sind.Du kannst auch UserInputService:GetConnectedGamepads() verwenden, um den richtigen Gamepad zu finden, um zu verwenden.

Das folgende Beispiel zeigt ein Nutzungsbeispiel für ein Tracking, wenn ein Gamepad vom Client getrennt wird.


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

Da dieses Ereignis lokal ausgelöst wird, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

gamepadNum: Enum.UserInputType

Das Enum.UserInputType des getrennten Gamepads.


InputBegan

Das Ereignis InputBegan wird ausgelöst, wenn ein Benutzer beginnt, über ein Mensch-Computer-Schnittstellen-Gerät zu interagieren (Mausknopf unten, Berührung beginnen, Tastaturknopf unten usw.).

Es kann verwendet werden, um den Beginn der Interaktion mit dem Benutzer zu verfolgen, z. B. wenn ein Benutzer zuerst mit einem GUI-Element, einem Gamepad usw. interagiert.Es erfasst keine Mouse-Radbewegungen.

Dieses Ereignis kann zusammen mit UserInputService.InputChanged und UserInputService.InputEnded verwendet werden, um zu verfolgen, wann der Benutzeingang beginnt, sich ändert und endet.

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Parameter

Eine InputObject Instanz, die Informationen über die Eingabe des Benutzers enthält.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das Ereignis InputChanged wird ausgelöst, wenn ein Benutzer ändert, wie er über ein Mensch-Computer-Schnittstellen-Gerät interagiert (Mausknopf nach unten, Berührung beginnen, Tastaturknopf nach unten usw.).

Um Ereignisse zu ignorieren, die von Roblox automatisch bearbeitet werden, wie das Scrollen in einem ScrollingFrame, überprüfe, dass das Argument gameProcessedEvent falsch ist.Dieses Ereignis kann zusammen mit UserInputService.InputBegan und UserInputService.InputEnded verwendet werden, um zu verfolgen, wann die Eingabe des Benutzers beginnt, sich ändert und endet.

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Parameter

Eine InputObject Instanz, die Informationen über die Eingabe des Benutzers enthält.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das Ereignis InputEnded wird ausgelöst, wenn ein Benutzer aufhört, über ein Mensch-Computer-Schnittstellen-Gerät zu interagieren (Mausknopf unten, Berührung beginnen, Tastaturknopf unten usw.).Dies ist nützlich, wenn Sie verfolgen, wann ein Benutzer eine Tastaturtaste, eine Maus- oder Schlüsselusw. freigibt.

Dieses Ereignis kann zusammen mit UserInputService.InputBegan und UserInputService.InputChanged verwendet werden, um zu verfolgen, wann der Benutzeingang beginnt, sich ändert und endet.

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Parameter

Eine InputObject Instanz, die Informationen über die Eingabe des Benutzers enthält.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das UserInputService Sprunganforderungs-Ereignis wird ausgelöst, wenn es eine Sprunganforderung vom Client gibt, zum Beispiel, wenn der Client die Leertaste oder den Sprung-Button auf dem Mobilgerät drückt.

Dieses Ereignis wird ausgelöst, wenn der Benutzer versucht, seinen springenzu machen.Das Standardverhalten reagiert auf eine Sprunganfrage, indem es die Eigenschaft des Spieler:inHumanoid.Jump auf wahr festlegt, was den springendes Charakters des Spieler:inauslöst.

Das Ereignis kann verwendet werden, um jedes Mal zu verfolgen, wenn ein Spieler springen möchte.Anstatt es zu verwenden, um einen Spieler zu springen, sollte es verwendet werden, um das Standard-Sprungverhalten zu ändern - wie das Ausschalten von Sprüngen.

Zum Beispiel druckt der Code unten jedes Mal "Springen", wenn der Spieler eine Anfragesendet.


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

Da dieses Ereignis mehrere Male für eine einzige Anfrageausgelöst wird, wird die Verwendung eines Debounce empfohlen.

Wenn du Schlüssel oder Schaltflächen mit anderen Aktionen verbinden möchtest, erwäge die Verwendung von Ereignissen wie UserInputService:GetKeysPressed() und UserInputService.InputBegan oder der ContextActionService.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.


Code-Beispiele

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

Das Ereignis UserInputService.LastInputTypeChanged wird immer dann ausgelöst, wenn der Client die Art und Weise ändert, wie er über ein Mensch-Computer-Schnittstellen-Gerät interagiert.(i.e.von MouseMovement zu MouseWheel oder von Thumbstick1 zu Thumbstick2).

Um den Wert des letzten eingebenzu erhalten, unabhängig davon, ob er sich geändert hat oder nicht, kannst du die UserInputService:GetLastInputType()-Funktion verwenden.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Parameter

lastInputType: Enum.UserInputType

Ein A Enum.UserInputType, das den letzten eingebenanzeigt.


Code-Beispiele

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

Mauszeigeraktion feuert ab, wenn der Benutzer eine bestimmte Actionausführt. Insbesondere Scrollen des Mausrads.

Parameter

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

TextBoxFocusReleased

Das Ereignis TextBoxFocusReleased wird ausgelöst, wenn ein Client den Fokus auf ein TextBox verliert, typischerweise, wenn ein Client den Texteintrag durch Drücken von Return oder Klicken/Berühren an anderer Stelle auf dem Bildschirm stoppt.

Zum Beispiel druckt der Code unten den Namen des TextBox verlorenen Fokus aus, wenn das Ereignis ausgelöst wird.


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

Es kann neben UserInputService.TextBoxFocused verwendet werden, um zu verfolgen, wann ein TextBox Fokus gewinnt und verliert.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch

Parameter

textboxReleased: TextBox

Die TextBox, die den Fokus verloren hat.


TextBoxFocused

Dieses Ereignis wird ausgelöst, wenn ein Gewinn-Fokus auf ein TextBox gerichtet wird, typischerweise, wenn ein Client auf ein Textfeld klickt/tippt, um mit dem Eingeben von Text zu beginnen.Dies wird auch ausgelöst, wenn ein Textfeld-Fokus mit TextBox:CaptureFocus() fokussiert wird.

Zum Beispiel druckt der Code unten den Namen des TextBox fokussierten aus, wenn das Ereignis ausgelöst wird.


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

Es kann neben UserInputService.FocusReleased verwendet werden, um zu verfolgen, wann ein Textfeld Fokus gewinnt und verliert.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch

Parameter

textboxFocused: TextBox

Das TextBox, das Fokus gewonnen hat.


TouchDrag

Parameter

dragDirection: Enum.SwipeDirection
numberOfTouches: number
gameProcessedEvent: boolean

TouchEnded

Das TouchEnded-Ereignis wird ausgelöst, wenn ein Benutzer seinen Finger vom Bildschirm eines TouchEnabled-Geräts loslässt und die Berührungseingabe mit dem Gerät beendet.

Dieses Ereignis kann verwendet werden, um zu bestimmen, wann ein Benutzer aufhört, den Bildschirm seines Geräts zu berühren.Es kann mit UserInputService.TouchStarted kombiniert werden, um zu bestimmen, wann ein Benutzer beginnt und aufhört, den Bildschirm zu berühren.

Zum Beispiel druckt der Code unten die Bildschirmposition aus, an der der Benutzer aufhört, den Bildschirm zu berühren.


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

Das Touch-Eingabeelement ist das gleiche Eingabeobjekt während der gesamten Lebensdauer des Touches.Also das Vergleichen von InputObjects, wenn sie Berührungsobjekte sind, ist gültig, um zu bestimmen, ob es sich um denselben Finger handelt.

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

Eine InputObject Instanz, die Informationen über die Eingabe des Benutzers enthält.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Feuert ab, wenn ein Benutzer mindestens einen Finger für kurze Zeit an derselben Bildschirmposition eines TouchEnabled-Geräts hält.

Dieses Ereignis kann verwendet werden, um zu bestimmen, wann ein Benutzer seinen Finger auf einem im Spiel GuiObject oder Element gedrückt hält.

Das folgende Beispiel druckt das state der langen Taste aus, wenn der Benutzer mindestens einen Finger für kurze Zeit in derselben Bildposition hält.Mögliche Zustände umfassen: Beginnen, Ändern, Beenden, Stornieren und Keine.


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)

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Es kann mit UserInputService.TouchStarted und UserInputService.TouchEnded kombiniert werden, um zu bestimmen, wann ein Benutzer beginnt und aufhört, die Bildschirmoberfläche zu berühren.

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

touchPositions: Array

Ein Array von Vector2 Objekten, das die Position der beteiligten Finger bei der Geste anzeigt.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Feuert, wenn ein Benutzer seinen Finger auf einem TouchEnabled, wie einem Tablet oder Smartphone, bewegt.

Dieses Ereignis ist nützlich, um zu verfolgen, ob ein Benutzer seinen Finger auf dem Bildschirm bewegt und wo der Benutzer seinen Finger bewegt.

Der Code unten zeigt die Berührung, die von ihrer vorherigen Position zu einer neuen Position auf einem TouchEnabled Gerät bewegt wird.Beachte, dass das InputObject.Position am übergebenen touch Parameter ein Vector3 ist, aber nur X und Y-Koordinaten enthält; Z ist immer 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)

Koppeln Sie dieses Ereignis mit UserInputService.TouchStarted und UserInputService.TouchEnded um festzustellen, wann ein Benutzer beginnt, den Bildschirm zu berühren, wie sich sein Finger bewegt, während er ihn berührt, und wann er aufhört, den Bildschirm zu berühren.

Um zu überprüfen, ob das Gerät eines Benutzers Touch unterstützt und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled.

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

Eine InputObject Instanz, die Informationen über die Eingabe des Benutzers enthält.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das TouchPan-Ereignis wird ausgelöst, wenn ein Benutzer mindestens einen Finger auf ein TouchEnabled.

Dieses Ereignis kann verwendet werden, um zu bestimmen, wann ein Benutzer seinen Finger über den Bildschirm eines TouchEnabled-Geräts bewegt - zum Beispiel, um das Camera in einem benutzerdefinierten Skript, das. PL: die Skriptszu drehen.

Das Snippet druckt unten "Geschwindigkeit des Touchdrags" und die Geschwindigkeit des Touch des Benutzers, wenn der Benutzer seinen Finger auf den Bildschirm zieht.


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

Schau dir eine andere nützliche UserInputService Funktion hier an UserInputService.TouchRotate .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

touchPositions: Array

Ein Array von Vector2 Objekten, die die Positionen der beteiligten Tasten (z. B. Finger) anzeigen, die an der Geste beteiligt sind.

totalTranslation: Vector2

Die Größe der Pan-Geste von Anfang bis Ende (in Pixeln).

velocity: Vector2

Die Geschwindigkeit der Pan-Geste (in Pixeln) pro Sekunde.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Feuert ab, wenn ein Benutzer zwei Finger auf dem Bildschirm eines TouchEnabled Geräts platziert und bewegt.

Zum Instanzdruckt das folgende Snippet aus, wie sich die Kamera-Zoom-Skala seit Beginn des Touch-Pinch geändert hat.


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

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht.Zum Beispiel werden Eingaben nicht erfasst, wenn das Fenster minimiert wird.Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

touchPositions: Array

Ein Array von Vector2s, das die Bildschirmposition in Pixeln der mit der Pinch-Geste beteiligten Finger anzeigt.

scale: number

Die Größe des Pinchs von Anfang bis Ende (in Pixeln) geteilt durch die Start-Pinch-Positionen.

velocity: number

Die Geschwindigkeit der Pinziergeste (in Pixeln) pro Sekunde.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das TouchRotate-Ereignis wird ausgelöst, wenn ein Benutzer zwei Finger auf einem TouchEnabled.

Zum Beispiel druckt der folgende Code aus, wie viel die Kamera seit Beginn der Berührungsrotierung gedreht wurde.


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

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Die Kernskripte, die die Kamera des Benutzers auf einem mobilen Gerät steuern, verwenden Code, der ähnlich wie dieses Ereignis funktioniert.Die beste Praxis für dieses Ereignis ist, es zu verwenden, wenn du ein mobiles Kamerasystem erstellst, um die Standard-Kernskripte zu überschreiben.

Siehe auch:

Parameter

touchPositions: Array

Ein Array von Vector2s, das die Positionen der Finger anzeigt, die an der Geste beteiligt sind.

rotation: number

Die Anzahl der Grad, die die Geste seit Beginn der Geste gedreht hat.

velocity: number

Die Änderung der Rotation (in Grad) geteilt durch die Dauer der Änderung (in Sekunden).

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das TouchStarted-Ereignis wird ausgelöst, wenn ein Benutzer seinen Finger auf ein TouchEnabled platziert, beginnend mit der Touch-Eingabe mit dem Gerät.

Dieses Ereignis kann verwendet werden, um zu bestimmen, wann ein Benutzer beginnt, den Bildschirm seines Geräts zu berühren.Es kann mit UserInputService.TouchEnded kombiniert werden, um zu bestimmen, wann ein Benutzer beginnt und aufhört, den Bildschirm zu berühren.

Das Touch-Eingabeelement ist das gleiche Eingabeobjekt während der gesamten Lebensdauer des Touches.Also das Vergleichen von InputObjects, wenn sie Berührungsobjekte sind, ist gültig, um zu bestimmen, ob es sich um denselben Finger handelt.

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

Eine InputObject Instanz, die Informationen über die Eingabe des Benutzers enthält.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das Ereignis TouchSwipe wird ausgelöst, wenn ein Benutzer seine Finger auf einem TouchEnabled Gerät wischt.

Dieses Ereignis kann verwendet werden, um zu bestimmen, wann ein Benutzer seine Finger auf dem Bildschirm seines Geräts wischt und die Richtung, in die der Benutzer gewischt hat.

Für eine genauere Verfolgung der Touch-Eingabebewegung verwenden Sie UserInputService.TouchMoved

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

swipeDirection: Enum.SwipeDirection

Ein Enum.SwipeDirection, der die Richtung anzeigt, in die der Benutzer gewischt hat.

numberOfTouches: number

Anzahl der Berührungen (z. B. Finger) in der Geste.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das TouchTap-Ereignis wird ausgelöst, wenn der Benutzer mit seinem Finger auf dem Bildschirm auf einem TouchEnabled berührt.

Dieses Ereignis wird unabhängig davon abgefeuert, ob der Benutzer die Spielwelt oder ein GuiObject -Element berührt.Wenn du nach einem Ereignis suchst, das nur abgefeuert wird, wenn der Benutzer die Weltberührt/antippt, verwende UserInputService.TouchTapInWorld.

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Parameter

touchPositions: Array

Ein Array von Vector2 Objekten, das die Position der Finger anzeigt, die an der Tap-Geste beteiligt sind.

gameProcessedEvent: boolean

Weist darauf hin, ob die SpielEngine diese Eingabe intern beobachtet und darauf reagiert hat.Im Allgemeinen bezieht sich dies auf die Verarbeitung von UI, also wenn ein Knopf von dieser Eingabe berührt oder angeklickt wurde, wäre .Das gilt auch für Eingabeereignisse, die über ContextActionService verbunden sind.


Code-Beispiele

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

Das TouchTapInWorld-Ereignis wird ausgelöst, wenn der Benutzer seine Finger auf dem Bildschirm auf einem TouchEnabled berührt.Es wird abgefeuert, wenn der Benutzer in die Welttippt.

Dieses Ereignis kann verwendet werden, um zu bestimmen, wann ein Benutzer auf den Bildschirm tippt und kein GuiObject -Element tippt.Wenn der Benutzer auf ein GUI-Element tippt, wird UserInputService.TouchTap stattdessen von TouchTapInWorld abgefeuert.

Um zu überprüfen, ob das Gerät eines Benutzers TouchEnabled ist, und dass Touch-Ereignisse initiierenwerden, siehe UserInputService.TouchEnabled .

Dieses Ereignis wird nur dann ausgelöst, wenn das Roblox-Clientfenster im Fokus steht. Eingaben werden zum Beispiel nicht erfasst, wenn das Fenster minimiert wird.

Da es nur lokal feuert, kann es nur in einem LocalScript verwendet werden.

Siehe auch:

Parameter

position: Vector2

Ein Vector2 , das die Position des Touches anzeigt.

processedByUI: boolean

Ob der Benutzer auf ein GUI-Element tippt.


Code-Beispiele

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

Das UserInputService Fensterfokusfreigegeben-Ereignis wird ausgelöst, wenn das Fenster des Roblox-Clients den Fokus verliert - typischerweise, wenn der Roblox-Client vom Benutzer minimiert wird.

Zum Beispiel druckt der Code unten "Fensterfokus freigegeben", wann immer der Roblox-Client den Fokus verliert.


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

Dieses Ereignis kann neben UserInputService.WindowFocused verwendet werden, um zu verfolgen, ob der Roblox-Client sich aktiv auf den Bildschirm eines Benutzers konzentriert.

Da es nur lokal feuert, kann es nur in einem LocalScript verwendet werden.


Code-Beispiele

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

Das UserInputService-Fensterfokus-Ereignis wird ausgelöst, wenn das Fenster des Roblox-Clients Fokus erhält - typischerweise, wenn der Roblox-Client maximiert/aktiv auf dem Bildschirm des Benutzers geöffnet ist.

Zum Beispiel druckt der Code unten "Fenster fokussiert", wann immer der Roblox-Client Fokus gewinnt.


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

Dieses Ereignis kann neben UserInputService.WindowFocusReleased verwendet werden, um zu verfolgen, ob der Roblox-Client sich aktiv auf den Bildschirm eines Benutzers konzentriert.

Da dieses Ereignis nur lokal feuert, kann es nur in einem LocalScript verwendet werden.


Code-Beispiele

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)