UserInputService

显示已弃用

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

无法创建
服务
未复制

UserInputService 是用于检测并捕获用户设备上可用不同类型的输入的服务。

该服务的主要目的是允许体验与多种可用输入形式合作,例如游戏手柄、触摸屏幕和键盘。它允许一个 LocalScript 执行不同的操作, depending on the device 和, 在 turn, 提供最佳体验给最终用户。

一些使用此服务的用例包括检测用户输入,当用户与图形用户界面、工具和其他游戏实例互动时。为了检测用户输入,服务必须查找服务事件。例如,服务可以检测到用户触摸移动设备屏幕使用 UserInputService.TouchStarted ,或连接游戏手��

由于此服务仅在客户端,它只会在使用 LocalScriptModuleScript 所需的情况下工作。 作为 LocalScript 的客户端,游戏中的用户只能检测自己的输入 - 而不是其他人的输入。

还请参阅 ContextActionService,一个允许您将函数绑定到多个用户输入的服务。

代码示例

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)

概要

属性

方法

活动

属性

AccelerometerEnabled

只读
未复制
读取并联

这个属性描述用户的设备是否有加速器

加速器是移动设备中找到的一个部件,用于测量加速度(速度变化)。

例如,以下代码示例显示了如何检查用户的设备是否拥有加速器。


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

如果设备有启用加速器,您可以使用 UserInputService:GetDeviceAcceleration() 函数或跟踪当设备的加速器改变使用 UserInputService.DeviceAccelerationChanged 事件时获取当前加速器的当前加速度。

作为 UserInputService 仅在客户端,此属性仅能在 LocalScript 中使用。

代码示例

Move a Ball using the Accelerometer

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

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

GamepadEnabled

只读
未复制
读取并联

此属性描述是否有用户使用的设备有可用的游戏手柄。如果游戏手柄可用,您可以使用 UserInputService:GetConnectedGamepads() 来检索连接的游戏手柄列表。

作为 UserInputService 仅在客户端,此属性仅能在 LocalScript 中使用。

还请参阅:

代码示例

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

只读
未复制
读取并联

这个属性描述用户的设备是否拥有陀螺仪。

陀螺仪是大多数移动设备的组件,可以检测方向和旋转速度。

如果用户的设备有陀螺仪,您可以使用 UserInputService:GetDeviceRotation() 函数和 UserInputService.DeviceRotationChanged 事件来将其 incorporate 到您的游戏。


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

作为 UserInputService 仅在客户端,此属性仅能在 LocalScript 中使用。

代码示例

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

只读
未复制
读取并联

此属性描述用户的设备是否拥有键盘。此属性是 true 当用户的设备有键盘可用,和 false 当它没有。

它可以用于确定用户是否拥有可用键盘 - 这可能是重要的,如果您想要检查是否可以使用 UserInputService:IsKeyDown()UserInputService:GetKeysPressed() 来检查键盘输入。

作为 UserInputService 仅在客户端,此属性仅能在 LocalScript 中使用。

代码示例

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

读取并联

此属性设置用户的鼠标在 Enum.MouseBehavior 枚列表上的行为。默认值是 ень MouseBehavior 默认值。

可以设置为三个值:

  1. 默认:鼠标在用户的屏幕上自由移动。
  2. 锁中心 : 鼠标锁定,无法从用户屏幕的中心移动。
  3. 锁定当前位置 : 鼠标锁定,当前位置在用户屏幕上的锁定时间内不能移动。

这个属性的值不会影响事件追踪鼠标移动的灵敏度。例如, GetMouseDelta 返回相同的 Vector2 屏幕位置,无论是否锁定或能够在用户的屏幕上自由移动。因结果,控制相机的脚本不会受到此属性的影响。

这个属性会被覆盖,如果 GuiButtonModal 已启用,玩家的右键未下降。

注意,如果鼠标锁定,UserInputService.InputChanged 仍然会在玩家移动鼠标时发射,并且将在鼠标所指向的位置传递。此外,如果玩家被踢出游戏,鼠标将被强行解锁。

作为 UserInputService 仅在客户端,此属性仅能在 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
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

未复制
读取并联

这个属性决定了用户的 Mouse 的敏感度。

灵敏度决定物理鼠标移动到游戏中的鼠标移动程度。这可以用来调整物理鼠标移动的灵敏度,例如 GetMouseDelta ,以及游戏中的鼠标移动。

这个属性不会影响鼠标标志的移动。也不会影响客户端在设置选项卡中找到的镜头敏感度设置,该设置还会调整事件跟踪鼠标移动的敏感度。

这个属性的最大值为 10 ,最小值为 0。低值表示低灵敏度,高值表示高灵敏度。

当敏感度为 0 时,跟踪鼠标移动的事件仍然会发生,但所有跟踪鼠标位置的参数和属性都会返回 Vector2.new()Vector3.new()InputObject.Delta

代码示例

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

只读
未复制
读取并联

此属性描述用户的设备是否拥有可用的鼠标。此属性是 true 当用户的设备有可用的鼠标,和 false 当它没有。


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

在使用 UserInputService 鼠标函数,例如 UserInputService:GetMouseLocation() 之前,请检查。

作为 UserInputService 仅在客户端,此属性仅能在 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
读取并联

MouseIcon 属性确定使用鼠标图像作为指针。如果为空,默认箭头将被使用。当鼠标悬停在某些UI对象上,例如ImageButtonTextButton、1> Class.Loaded1>或4> Class.ProximityPrompt4>,这个图像

要完全隐藏鼠标,请不要使用透明图像。 相反,将 Class.UserInputService.MouseIconEnabled 设置为 false。

代码示例

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

读取并联

此属性决定是否显示 Mouse 图标,当 true 鼠标图标可见,当 false 它不是。

例如,下面的代码示例隐藏了鼠标的标志。


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

作为 UserInputService 仅在客户端,此属性仅能在 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

只读
未复制
读取并联

此属性描述屏幕键盘的位置以像素计数。键盘的位置是 Vector2.new(0, 0) 当它不可见时。

作为 UserInputService 仅在客户端,此属性仅能在 LocalScriptScript 中使用,设置 1> Class.BaseScript.RunContext|RunContext1> 为 4> Enum.RunContext.Client4> 。

还请参阅OnScreenKeyboardVisibleOnScreenKeyboardSize

代码示例

UserInputService.OnScreenKeyboardPosition

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

OnScreenKeyboardSize

只读
未复制
读取并联

此属性描述屏幕上的键盘在像素级别上的大小。键盘的大小是 Vector2.new(0, 0) 当它不可见时。

作为 UserInputService 仅在客户端,此属性仅能在 LocalScriptScript 中使用,设置 1> Class.BaseScript.RunContext|RunContext1> 为 4> Enum.RunContext.Client4> 。

还请参阅OnScreenKeyboardVisibleOnScreenKeyboardPosition

OnScreenKeyboardVisible

只读
未复制
读取并联

此属性描述屏幕上是否显示当前屏幕键盘。

作为 UserInputService 仅在客户端,此属性仅能在 LocalScriptScript 中使用,设置 1> Class.BaseScript.RunContext|RunContext1> 为 4> Enum.RunContext.Client4> 。

还请参阅OnScreenKeyboardSizeOnScreenKeyboardPosition

TouchEnabled

只读
未复制
读取并联

此属性描述用户当前设备是否有可用的触摸屏幕。

属性用于确定用户的设备是否拥有触摸屏幕,从而是否触发触摸事件。如果触摸Enabled是真的,你可以使用 UserInputService.TouchStartedUserInputService.TouchEnded 来跟踪当用户开始触摸屏幕时触摸事件是否发生。

以下代码示例打印用户设备是否有触摸屏幕。


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

还请参阅:

代码示例

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

只读
未复制
读取并联

此属性描述用户是否使用虚拟现实(VR)设备。

如果启用了 VR 设备,您可以通过使用“UserInputService:GetUserCFrame()”等函数与其位置和移动互动。您还可以使用“UserInputService.UserCFrameChanged”事件来反应虚拟现实设备的移动。


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

作为 UserInputService 仅在客户端,此属性仅能在 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

方法

GamepadSupports

此函数返回给定的 Enum.UserInputType 游戏手柄是否支持与给定的 Enum.KeyCode 相对应的按钮。 此函数用于确定有效的游戏手柄输入。

要确定哪个 Enum.UserInputType 游戏手柄是连接的,请使用 UserInputService:GetConnectedGamepads()

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。

还请参阅:

参数

gamepadNum: Enum.UserInputType

游戏手柄的 Enum.UserInputType

gamepadKeyCode: Enum.KeyCode

该问题的按钮的 Enum.KeyCode


返回

游戏手柄是否支持与给定的 Enum.KeyCode 相对应的按钮。

代码示例

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

此函数将返回一个 Enum.UserInputType 游戏手柄的列表。如果没有游戏手柄连接,此列表将为空。此外,它只会返回游戏手柄的对象,例实例游戏手柄1的对象。因此,此事件将返回一个连接的 Gamepad1 对象,而不是键盘对象。

例如,以下代码片段检索连接的游戏手柄并将其存储在 连接游戏手柄 变量中。


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

要检查特定游戏手柄是否连接,请使用 UserInputService:GetGamepadConnected()

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。

还请参阅:


返回

GamepadManager|游戏手柄管理器|游戏手柄型号 对应的游戏手设备型号。

代码示例

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

获取设备加速函数确定用户设备的当前加速。它返回一个 InputObject ,该描述设备当前加速的描述。

为了使其工作,用户的设备必须有一个启用加速器的设备。要检查用户的设备是否拥有加速器,您可以检查 UserInputService.AccelerometerEnabled 属性。

如果您想跟踪当用户的设备的加速度变化而不是时,您可以使用 UserInputService.DeviceAccelerationChanged 事件。

由于它只能在本地发射,因此它只能用在 LocalScript 中。


返回

代码示例

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

此函数返回一个 InputObject 描述设备当前重力向矢量力的描述。

重力 vector 由设备的 orientierung 与实际世界的重力 force 决定。 例实例,如果设备完美地立即(portrait),重力 vector 是 Vector3.new(0, 0, -9.18)。 如果左侧的设备向下指向,重力 vector 是 Vector3.new(9

这个函数可能用于让用户的设备在游戏中影响或控制重力或移动游戏中的对象,例如球。

重力仅为使用启用了陀螺仪的设备 - 例如移动设备 - 跟踪。

要检查用户的设备是否有启用的陀螺仪,请检查 UserInputService.GyroscopeEnabled 的值。如果设备有启用的陀螺仪,您还可以使用 UserInputService.DeviceGravityChanged 事件来跟踪当重力在设备上的用户时是否发生了变化。

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。


返回

代码示例

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

此函数返回一个 InputObject 和一个 CFrame 描述设备当前旋转向矢量力的设备。

这是用输入对象发射。 位置 属性的输入对象是一个 Enum.InputType.Gyroscope ,该跟踪在每个本地设备轴上的总旋转。

设备旋转只能在 gyroscope 的设备上追踪。

由于此函数只能在本地发生,它只能在 LocalScript 中使用。


返回

包含两个属性的表式:

  1. Delta 属性描述上一次发生的旋转量
  2. CFrame 是设备的当前旋转对于其默认参考框的旋转关系。

代码示例

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

此函数将返回客户端当前聚焦的TextBox。一个 TextBox 可以通过用户手动选择返回,或使用TextBox:CaptureFocus() 函数来强制选择。如果没有选择 TextBox,此函数将返回

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。

还请参阅:


返回

代码示例

Ignore User Input When a TextBox Is Focused

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

GetGamepadConnected

此函数返回游戏手柄是否连接到客户端。

这可以用来检查特定游戏手柄,例如 'Gamepad1' 是否连接到客户端的设备。

要获取所有连接的游戏手柄的列表,请使用 UserInputService:GetConnectedGamepads()

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。

还请参阅:

参数

gamepadNum: Enum.UserInputType

游戏手柄的 Enum.UserInputType


返回

是否连接游戏手柄控制器,并且使用 Enum.UserInputType

代码示例

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

此函数为所有可用输入在指定 InputObjects 游戏手柄上的所有可用输入返回一个阵列,代表每个输入的最后输入状态。

要找到连接的游戏手柄的 UserInputTypes,请使用 UserInputService:GetConnectedGamepads()

由于此函数只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

gamepadNum: Enum.UserInputType

ень UserInputType 与游戏手柄相对应。


返回

Class.InputObject|InputObjects 表示所有可用输入的当前状态。

GetImageForKeyCode

ContentId

此方法使用 Enum.KeyCode 并将要求的图像返回当前连接的游戏手柄设备(仅限于 Xbox、PlayStation 和 Windows)。这意味着如果连接控制器是 Xbox 控制器,用户会看到 Xbox 资产。同样,如果连接设备是 PlayStation 控制器,用户会看到 PlayStation 资产。如果要使用自定

参数

keyCode: Enum.KeyCode

获取相关图像的 Enum.KeyCode


返回

ContentId

返回的图像资源ID。

代码示例

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

此函数返回一个 InputObjects 阵列,与当前按下的键相关。

此阵列可以通过迭代以确定哪些键当前正在按,使用 InputObject.KeyCode 值。

要检查特定键是否被按下,请使用 UserInputService:IsKeyDown()

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。


返回

Class.InputObject|InputObjects 与当前按钮组合在一起的阵列。

代码示例

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

此函数返回“枚列.UserInputType”与用户最近输入相关。

例如,如果前一次输入用户按下空格键,Enum.UserInputType 将返回键盘

Class.UserInputService.LastInputTypeChanged 事件可以用于跟踪用户使用 Enum.UserInputType 的最后一次使用。

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。


返回

与用户最近的输入相关的 Enum.UserInputType

代码示例

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

此函数返回一个相应于当前按钮被按下的鼠标按钮阵列。

跟踪此功能的鼠标按钮包括:


<tr>
<td>鼠标按钮1</td>
<td>左侧鼠标按钮。</td>
</tr>
<tr>
<td>鼠标按钮 2</td>
<td>右侧鼠标按钮。</td>
</tr>
<tr>
<td>鼠标按钮3</td>
<td>中间的鼠标按钮。</td>
</tr>
名称描述

如果用户在调用该函数时没有按任何鼠标按钮,它将返回一个空的数组列。

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。


返回

Class.InputObject|InputObjects 阵列,对应当前持有的鼠标按钮。

代码示例

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

此函数将玩家的 Mouse 位置在最后一张渲染框中的变化,以 Vector2 的形式返回。 此函数只会工作,如果鼠标使用 UserInputService.MouseBehavior 属性锁定。 如果没有锁定,返回的 2>Datatype.Vector22> 值将为零

鼠标的灵敏度,由客户端的设置和 UserInputService.MouseDeltaSensitivity 决定,会影响结果。

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。


返回

改变鼠标的移动。

代码示例

Getting Mouse Delta

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

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

GetMouseLocation

此函数返回一个 Vector2 代表玩家当前屏幕位置的代码,在毫米相对于左上角。这不会考虑 Mouse 的设置。

如果鼠标指针的位置是 offscreen 或玩家的设备没有鼠标,返回的值将被确定。

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。


返回

一个 Vector2 代表鼠标当前屏幕位置的像素。

代码示例

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

此函数返回一个游戏手柄 UserInputTypes 连接并启用为 GUI 导航的阵列。此列表是按优先级递归的,因此它可以被迭代以确定哪个游戏手柄有导航控件。

连接的游戏手柄是否是导航游戏手柄只会决定哪个游戏手柄控制导航 GUI。这不会影响导航控件。

由于 UserInputService 仅在客户端,因此此功能仅能在 LocalScript 中使用。

还请参阅:


返回

Enums.UserInputType|UserInputTypes 可用于 GUI 导航,按优先级下降排序。

GetStringForKeyCode

获取键码代码 返回一个代表用户应该按下以输入指定 Enum.KeyCode 的键,并且考虑其键盘布局。对于需要一些调整器的键代码,此函数将键代码返回键以及调整器。在下面的例子中,有助于说明。

使用 Roblox 时,如果使用者使用非 QWERTY 键盘布局,键码将映射到相当于 QWERTY 位置的位置。例如,在 AZERTY


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

在 QWERTY 键盘上的例子


<tbody>
<tr>
<td><code>枚数。键码。Q</code></td>
<td><code>Q</code></td>
</tr>
<tr>
<td><code>enum.keycode.w</code></td>
<td><code>W</code></td>
</tr>
<tr>
<td><code>enum.keycode.Equals</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>枚列代码。</code></td>
<td><code>2</code> 因为 <code>@</code> 是用 <kbd>Shift</kbd> 键打字 <kbd>2</kbd></td>
</tr>
</tbody>
钥匙代码返回值

在 AZERTY 键盘上的例子


<tbody>
<tr>
<td><code>枚数。键码。Q</code></td>
<td><code>A)</code></td>
</tr>
<tr>
<td><code>enum.keycode.w</code></td>
<td><code>Z</code></td>
</tr>
<tr>
<td><code>enum.keycode.Equals</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>枚列代码。</code></td>
<td><code>É</code></td>
</tr>
</tbody>
钥匙代码返回值

游戏手柄使用

GetStringForKeyCode() 返回最近连接的游戏手柄的 Enum.KeyCode 字符串映射。如果控制器不支持,该函数将返回请求的键验证码的默认字符串转换。

下面的例子显示了您如何为ButtonA 定制资源:


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

游戏手柄映射

方向键代码根据设备不存在任何差异。 Enum.KeyCode.ButtonSelect 在某些情况下具有稍微不同的行为。 使用 PlayStation 地图确保用户看到正确的按钮。


<tbody>
<tr>
<td><code>枚举.KeyCode.ButtonA</code></td>
<td><code>按钮交叉点</code></td>
<td><code>按钮A</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonB</code></td>
<td><code>按钮圆圈</code></td>
<td><code>按钮B</code></td>
</tr>
<tr>
<td><code>枚数。键码。按钮 X</code></td>
<td><code>按钮方块</code></td>
<td><code>按钮 X</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonY</code></td>
<td><code>按钮三角形</code></td>
<td><code>按钮Y</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonL1</code></td>
<td><code>按钮L1</code></td>
<td><code>按钮LB</code></td>
</tr>
<tr>
<td><code>枚数。键码。按钮 L2</code></td>
<td><code>按钮L2</code></td>
<td><code>按钮LT</code></td>
</tr>
<tr>
<td><code>枚数。键码。按钮。L3</code></td>
<td><code>按钮L3</code></td>
<td><code>按钮LS</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonR1</code></td>
<td><code>按钮R1</code></td>
<td><code>按钮 RB</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonR2</code></td>
<td><code>按钮R2</code></td>
<td><code>按钮RT</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonR3</code></td>
<td><code>按钮R3</code></td>
<td><code>按钮 RS</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonStart</code></td>
<td><code>按钮选项)</code></td>
<td><code>按钮开始</code></td>
</tr>
<tr>
<td><code>枚数。键码。按钮选择</code></td>
<td><code>按钮触摸板</code> 和 <code>按钮共享</code></td>
<td><code>按钮选择</code></td>
</tr>
</tbody>
钥匙代码PlayStation 返回值Xbox 返回价值

键码系统图像

使用 Enum.KeyCode 作为用户界面上的图像,例如用户界面上的 ImageLabel ,您可以使用以下传奇图标。但是,您可以使用 GetImageForKeyCode() 作为更现代的交叉平台方法来恢复 Xbox 和 PlayStation 控制


<tbody>
<tr>
<td><code>枚数。键码。按钮 X</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>枚举.KeyCode.ButtonY</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxY.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxY.png</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonA</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxA.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxA.png</code></td>
</tr>
<tr>
<td><code>枚举.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>枚数。键码。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>枚数。键码。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>枚数。键码。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>枚数。键码。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>枚数。键码。按钮选择</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>枚举.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>枚举.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>枚举.KeyCode.ButtonR1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRB.png</code></td>
</tr>
<tr>
<td><code>枚数。键码。按钮 L2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLT.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxLT.png</code></td>
</tr>
<tr>
<td><code>枚举.KeyCode.ButtonR2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRT.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRT.png</code></td>
</tr>
<tr>
<td><code>枚数。键码。按钮。L3</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>枚举.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>枚数。键码。拇指1</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>枚数。键码。拇指 2</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>枚列代码返回空格</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>枚列代码返回</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>枚列代码左Shift</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>枚数。键码。右Shift</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>枚列代码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>枚数。KeyCode。Apostrophe</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>枚数。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>枚数。键码。回号</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>枚数.KeyCode.期间</code></td>
<td>
<img src="../../../assets/scripting/controls/period.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/期间.png</code></td>
</tr>
<tr>
<td><code>枚列代码空间</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>
钥匙代码图像资产 ID

参数

keyCode: Enum.KeyCode

返回

GetSupportedGamepadKeyCodes

此函数返回一个 KeyCodes 游戏手柄与指定 Enum.UserInputType 支持的游戏代码库。

此功能可用于确定哪些键码由连接的游戏手柄支持,并且不支持的。要确定特定键码是否支持,请使用 UserInputService:GamepadSupports()

如果在非存在或不连接的游戏手柄上调用,该函数将返回一个空的数组。

作为 UserInputService 仅在客户端,此功能仅可在 LocalScript 中使用。

还请参阅:

参数

gamepadNum: Enum.UserInputType

游戏手柄的 Enum.UserInputType


返回

游戏手柄上支持的KeyCodes阵列。

代码示例

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

此函数检查特定游戏手柄上是否按下特定按钮。它返回 true 如果 gamepad 有指定的 button 按下,否则它返回 false。

有效的用户输入类型

指定的游戏手柄应该是以下 UserInputType 枚值之一:


<tr>
<td>枚数。UserInputType.Gamepad1-8</td>
</tr>
名称

有效的钥匙代码

指定的按钮应该是以下 KeyCodes 列表中的一个:


<tr>
<td>枚数。键码。按钮 X</td>
</tr>
<tr>
<td>枚数。键码。按钮Y</td>
</tr>
<tr>
<td>枚数。键码。按钮 A</td>
</tr>
<tr>
<td>枚数。键码。按钮 B</td>
</tr>
<tr>
<td>枚数。键码。按钮R1</td>
</tr>
<tr>
<td>枚数。键码。按钮L1</td>
</tr>
<tr>
<td>枚数。键码。按钮R2</td>
</tr>
<tr>
<td>枚数。键码。按钮 L2</td>
</tr>
<tr>
<td>枚数。键码。按钮R3</td>
</tr>
<tr>
<td>枚数。键码。按钮L3</td>
</tr>
<tr>
<td>枚数。键码。按钮开始</td>
</tr>
<tr>
<td>枚数。键码。按钮选择</td>
</tr>
<tr>
<td>枚数。键码。DPadLeft</td>
</tr>
<tr>
<td>枚数。键码。DPadRight</td>
</tr>
<tr>
<td>枚数。键码。DPadUp</td>
</tr>
<tr>
<td>枚数。键码。DPadDown</td>
</tr>
名称

这可以用来检查特定按钮,例如 A,是否被按住。例如:


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

由于 UserInputService 仅在客户端,因此此功能仅能在 LocalScript 中使用。

还请参阅:

参数

gamepadNum: Enum.UserInputType

游戏手柄的 Enum.UserInputType

gamepadKeyCode: Enum.KeyCode

指定按钮的 Enum.KeyCode


返回

是否按下指定的游戏手柄上的游戏手柄按钮。

代码示例

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

此函数返回用户是否按住与指定的 Enum.KeyCode 关联的钥匙。它返回 true 如果指定的钥匙被按下,或 false 如果未被按下。

这可以用来检查空格键,例如空格键是否被按下。 例如:


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

要恢复用户按下的所有按键列表,请使用 UserInputService:GetKeysPressed() 函数。

由于 UserInputService 仅在客户端,因此此功能仅能在 LocalScript 中使用。

还请参阅:

参数

keyCode: Enum.KeyCode

KeyCode 的键匙。


返回

是否按住指定的钥匙。

代码示例

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

此函数使用鼠标按钮Enum.UserInputType 并返回一个指示当前是否按下的Boolean。

检查鼠标按钮的值取决于 Enum.UserInputType 值传递给函数作为参数。例如:


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

由于 UserInputService 仅在客户端,因此此功能仅能在 LocalScript 中使用。

参数

mouseButton: Enum.UserInputType

鼠标按钮的 Enum.UserInputType


返回

是否按下当前鼠标按钮。

代码示例

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

此函数返回 true 如果指定的 Enum.UserInputType 游戏手柄允许控制 GUIs 的导航和选择。

如果您想要设置一个导航游戏手柄,您可以使用 UserInputService:SetNavigationGamepad()。您还可以使用 UserInputService:GetNavigationGamepads() 以获取所有导航游戏手柄的列表。

例如,下面的代码检查游戏手柄1是否为导航游戏手柄:


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

无论导航是否可用,您可以使用“用户输入/获取连接游戏板”检索所有连接的游戏板。

由于 UserInputService 仅在客户端,因此此功能仅能在 LocalScript 中使用。

还请参阅:

参数

gamepadEnum: Enum.UserInputType

指定的游戏手柄的 Enum.UserInputType


返回

是否指定的游戏手柄是导航游戏手柄。

RecenterUserHeadCFrame

void

此函数将 VR 头set 的 CFrame 重置到用户穿戴的头set 的当前方向。这意味着头set 的当前方向已设置为 CFrame.new()

使用此函数将头戴式耳机CFrame移动到播放区域的中心,如果它看起来有奇怪的 Offset。

这与 VRService 函数相同, VRService:RecenterUserHeadCFrame()

由于 UserInputService 仅在客户端,因此此功能仅能在 LocalScript 中使用。


返回

void

代码示例

UserInputService:RecenterUserHeadCFrame

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

SetNavigationGamepad

void

SetRotationGamepad 游戏手柄设置是否允许指定的 EnumeratorType 游戏手柄移动 GUI 导航器。一个允许移动 GUI 导航器的游戏手柄被视为导航游戏手柄。

如果 启用 参数作为 true ,游戏手柄可以移动 GUI 导航器。如果参数是 false ,游戏手柄无法移动 GUI 导航器。

如果您想要检查指定的游戏手柄是否为导航游戏手柄,您可以使用 UserInputService:IsNavigationGamepad() 函数。您还可以使用 UserInputService:GetNavigationGamepads() 来检索所有导航游戏手柄。

由于 UserInputService 仅在客户端,因此此功能仅能在 LocalScript 中使用。

还请参阅:

参数

gamepadEnum: Enum.UserInputType

指定的游戏手柄的 Enum.UserInputType

enabled: bool

是否允许指定的游戏手柄移动 GUI 导航器。


返回

void

代码示例

UserInputService:SetNavigationGamepad

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

活动

DeviceAccelerationChanged

装置加速器变更事件触发,当用户移动一个具有加速器的设备。

加速器是移动设备中找到的一个部件,用于测量加速度(速度变化)。

要确定用户的设备是否启用加速器,请参阅UserInputService.AccelerometerEnabled

此事件可以用来跟踪具有加速器的设备的移动。一个示例使用包括移动玩家角色,当移动设备加速时。

此事件还可以与 UserInputService:GetDeviceAcceleration() 用于确定用户设备的当前移动方向,如果设备有加速器。

此事件仅在本地发生 - 这意味着仅有移动设备的玩家才能使用它,它只会在 LocalScript 中工作。

参数

acceleration: InputObject

一个 InputObject ,拥有一个 UserInputType 的 'Accelerometer' ,以及一个 2>Class.InputObject.Position|Position2> ,显示每个本地设备轴上的重力强度。


代码示例

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

UserInputService.DeviceGravityChanged 事件触发时,装设备的重力 Vector3 会改变在有加速器的装置上。

设备置的重力向量代表装设备的 X、Y 和 Z 轴上的重力。 虽然重力不会改变,但随着装置旋转和改变方向,该向量上的力与每个轴上的力的变化。 力值的重量向量在每个轴上的 -1 到 1 之间。

加速器是移动设备中找到的一个部件,用于测量加速度(速度变化)。

这个事件可以用于确定用户设备上重力的实际世界方向。这甚至可以用于在游戏中模拟重力在用户设备上的力量,例如在游戏中的对象(请参阅下面的示例)。

要检查用户的设备是否有启用的加速器,请参阅UserInputService.AccelerometerEnabled。如果设备有启用加速器,您可以使用UserInputService:GetDeviceGravity()函数获取用户设备上的当前重力。

参数

gravity: InputObject

一个 InputObject ,具有一个 InputObject.Position 属性,显示每个本地设备轴上的重力力。这个位置可以用作一个方向来确定重力对于设备的方向。


代码示例

Move a Ball using the Accelerometer

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

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

DeviceRotationChanged

DeviceRotationChanged 事件触发,当用户旋转具有陀螺仪的设备。

陀螺仪是大多数移动设备的组件,可以检测方向和旋转速度。

当追踪设备的方向时,该事件有助于跟踪用户旋转设备时如何变化。要确定当前设备旋转是否为UserInputService:GetDeviceRotation(),您可以使用 Class.UserInputService:GetDeviceRotation() 函数。

要检查用户的设备是否启用了陀螺仪,并且该事件会发触发,请参阅UserInputService.GyroscopeEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

参数

rotation: InputObject

一个 InputObject 提供有关设备旋转的信息。InputObject.Position 代表一个新的旋转位置,Vector3 代表一个旋转位置在 2>Datatype.Vector32> 位置的变化。

cframe: CFrame

一个 CFrame 代表设备当前方向。


代码示例

Create a Gyroscopic Camera

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

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

GamepadConnected

游戏手柄连接事件触发,当游戏手柄连接到客户端时。

由于 Roblox 游戏支持多个控制器,因此此事件有助于与 UserInputService.GamepadDisconnected 事件配对来跟踪哪些控制器/游戏手柄是活跃的。您还可以使用 UserInputService:GetConnectedGamepads() 来找到正确的游戏手柄以使用。

下面的例子显示了一个游戏手柄连接到客户端时的跟踪示例。


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

如果您想要查看连接到哪些设备,您可以使用 UserInputService:GetConnectedGamepads() 函数。

当本事件发生时,它只能在 LocalScript 中使用。

还请参阅:

参数

gamepadNum: Enum.UserInputType

连接游戏手柄的 Enum.UserInputType


GamepadDisconnected

GamepadDisconnected事件触发,当游戏手柄被分离。

由于 Roblox 游戏支持多个控制器,因此此事件有助于与 UserInputService.GamepadConnected 事件配对来跟踪哪些控制器/游戏手柄是活跃的。您还可以使用 UserInputService:GetConnectedGamepads() 来找到正确的游戏手柄以使用。

下面的例子显示了一个游戏手柄从客户端断开时的跟踪示例。


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

当本事件发生时,它只能在 LocalScript 中使用。

还请参阅:

参数

gamepadNum: Enum.UserInputType

枚列表.UserInputType 的 disconnected 游戏手柄。


InputBegan

输入开始事件触发,当用户开始通过人类-计算机界面设备(鼠标按钮向下,触摸开始,键盘按钮向下等等)进行交互时。

它可以用于跟踪用户与 GUI 元素、游戏手柄等的交互开始时间,例如当用户首次与 GUI 元素互动时。它不会捕获鼠标轮动。

此事件可以与 UserInputService.InputChangedUserInputService.InputEnded 一起使用,以跟踪当用户输入开始、变更和结束时。

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

参数

一个 InputObject 实例,包含用户的输入信息。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

输入变更事件触发,当用户改变通过人类-计算机界面设备(鼠标按钮向下,触摸开始,键盘按钮向下等)的交互方式。

要忽略 Roblox 自动处理的事件,例如在 ScrollingFrame 中滚动,检查 游戏处理事件 参数是否为 false。 此事件可以与 UserInputService.InputBegan 和 1> Class.UserInputService.InputEnded1> 一起使用,以跟踪当用户输入

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

参数

一个 InputObject 实例,包含用户的输入信息。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

输入结束事件触发,当用户停止通过人类-计算机界面设备(鼠标按钮向下,触摸开始,键盘按钮向下等)交互时。 这很有用,当用户释放键盘按钮,鼠标按钮向下,触摸屏幕输入等。

此事件可以与 UserInputService.InputBeganUserInputService.InputChanged 一起使用,以跟踪用户输入开始、变更和结束。

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

参数

一个 InputObject 实例,包含用户输入的信息。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

Class.UserInputService 跳转请求事件触发,当客户端发出跳转请求时,例如当客户端按下移动设备上的空格键或跳转按钮。

这个事件会触发,每当用户尝试跳过他们的 Player.Character 跳跃。默认行为会在玩家设置其 Humanoid.Jump 属性为 true,从而使玩家的角色跳跃。

该事件可以用于跟踪玩家每次想要跳跃的时候。 而不是使用它来让玩家跳跃,这应该用来更改默认跳跃行为 - 例如禁用跳跃。

例如,下面的代码每次玩家发送跳跃请求时都会打印“跳跃”。


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

由于此事件为单个跳跃请求触发多次,使用 弹跳减震器 是最佳选择。

如果您想要将钥匙或按钮连接到其他操作,请考虑使用事件,例如 UserInputService:GetKeysPressed()UserInputService.InputBeganContextActionService

由于这个事件只会在本地发生,它只能在 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

Class.UserInputService.LastInputTypeChanged 事件触发时间发生在客户端改变通过人类-计算机界面设备交互方式时。(例如从鼠标移动到鼠标轮或从拇指1到拇指2)。

无论输入类型是否改变,您都可以使用 UserInputService:GetLastInputType() 函数获取最后输入类型。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

参数

lastInputType: Enum.UserInputType

一个 Enum.UserInputType 指示最后一个输入类型。


代码示例

Hide Mouse During Keyboard Input

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

PointerAction

PointerAction 会在用户执行特定指针操动作时触发。 具体地,滚动鼠标轮。

参数

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

TextBoxFocusReleased

当客户端在 TextBox 上失去焦点时,TextBox 聚焦发布事件触发 - 通常是客户端在按返回或单击/触摸屏幕上的任何地方时失去文本输入。

例如,下面的代码打印了 TextBox 失焦时事件触发时的名称。


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

它可以与 UserInputService.TextBoxFocused 一起使用,以跟踪当 TextBox 获得和失去焦点时。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

textboxReleased: TextBox

失去聚焦的 TextBox


代码示例

TextBoxFocusReleased

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

TextBoxFocused

当 TextBoxFocused 事件触发时,一个客户端点击/触摸一个文本框以开始输入文本。当 TextBoxFocused 事件使用 <a href="/reference/engine/datatypes">Class.DT</a> 时,这也会触发。

例如,下面的代码打印了 TextBox 专注时打印的名称。


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

它可以与 UserInputService.FocusReleased 一起使用,以跟踪当文本框在聚焦时获得和失去焦点。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

textboxFocused: TextBox

获得焦点的 TextBox


代码示例

Modifying a TextBox on Focused and FocusReleased

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

TouchEnded

触及结束事件触发,当用户从触摸设备的屏幕上释放他们的手指时,结束用户的触摸输入。

此事件可以用于确定用户是否停止触摸他们的设备屏幕。它可以与 UserInputService.TouchStarted 配对,用于确定用户是否开始并停止触摸屏幕。

例如,下面的代码打印了用户停止触摸屏幕的位置。


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

触摸输入对象是触摸的整个生命时间的触摸输入对象。因此,比较 InputObjects 当触摸对象是触摸对象时,是否为同一个手指是有效的。

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

一个 InputObject 实例,包含用户的输入信息。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

用户在触摸启用的设备上按住至少一个手指,持续时间不足屏幕位置。

此事件可以用来确定用户是否在游戏中的 GUI 或元素上按住指针。

下面的例子打印了用户在同一屏幕位置上按住至少一个手指的时间 state 的长按。可能的状态包括:开始更改、1>结束1>、4>取消4>和7>无7>。


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)

要检查用户的设备是否触摸启用,触摸事件是否会触发,请参阅UserInputService.TouchEnabled

它可以与 UserInputService.TouchStartedUserInputService.TouchEnded 来确定用户是否开始或停止触摸屏幕。

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

touchPositions: Array

Datatype.Vector2 对象,表示手势中涉及的手指的位置。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

触摸移动事件触发,当用户在触摸启用的设备上移动其手指。

此事件可以用于确定触摸启用的设备屏幕上的用户是否移动他们的手指。它可能有助于跟踪用户是否在屏幕上移动他们的手指,以及用户在移动他们的手指的位置。

下面的代码打印“触摸从”以前的 Vector2 位置“到”用户在 TouchEnabled 设备上的触摸的新 Vector2 位置。


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)

它可以与 UserInputService.TouchStartedUserInputService.TouchEnded 配对,以确定用户开始触摸屏幕时,他们的手指移动在触摸屏幕时,并且当他们停止触摸屏幕时。

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

一个 InputObject 实例,包含用户的输入信息。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

触摸板事件触发,当用户在至少一个手指在 Class.UserInputService.TouchEnabled|TouchEnabled 设备上拖动时。

此事件可以用于确定用户是否将手指抚摸触悉启用的设备屏幕 - 例如在自定义的摄像头脚本中旋转 Camera

下面的叙述打印“触摸速度拖动”,并且跟随用户拖动用户手指到屏幕上时的速度。


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

在这里查看另一个有用的 UserInputService 函数 UserInputService.TouchRotate

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

touchPositions: Array

Datatype.Vector2 对象,表示触摸中涉及的触摸位置(例如手指)。

totalTranslation: Vector2

从开始到结束的平底锅手势的大小(以像素计)。

velocity: Vector2

平移速度(以像素每秒)。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

发生在用户放置和移动两个手指到 TouchEnabled 设备的屏幕时。

例实例,下面的代码显示了自从触摸开始以来,镜头缩放量的变化。


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

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生于 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。 此事件仅在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

touchPositions: Array

Datatype.Vector2|Vector2s 阵列,表示屏幕位置,以像素计表示手指在捏合手势中涉及的位置。

scale: number

从开始到达终点(以像素为单位)的抖动量。

velocity: number

每秒钟的点击手势的速度(以像素为单位)。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

触摸旋转事件触发,当用户在 TouchEnabled 设备上旋转两个手指。

例如,以下代码打印了触摸旋转开始以来相机旋转的角度。


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

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

在移动设备上控制用户的相机的核心脚本使用类似于此事件的代码。 对于此事件的最佳实践是使用它来创建移动相机系统来覆盖默认核心脚本。

还请参阅:

参数

touchPositions: Array

Datatype.Vector2|Vector2s 阵列,表示与手势有关的手指位置。

rotation: number

从手势开始旋转的度数。

velocity: number

改变旋转角度(以度数)除以更改时间(以秒)。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

触摸开始事件触发,当用户将他们的手指放在 TouchEnabled 设备上,开始触摸输入,并且设备上的触摸输入开始显示。

此事件可以用于确定用户是否开始触摸他们的设备屏幕。它可以与 UserInputService.TouchEnded 配对,用于确定用户是否开始并停止触摸屏幕。

触摸输入对象是触摸的整个生命时间的触摸输入对象。因此,比较 InputObjects 当触摸对象是触摸对象时,是否为同一个手指是有效的。

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

一个 InputObject 实例,包含用户的输入信息。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

触摸棒动作触发时,当用户用手指在 TouchEnabled 设备上滑动时,触摸棒动作触发。

此事件可以用于确定用户是否在他们的设备屏幕上抚摸他们的手指,以及用户抚摸的方向。

了解有关触摸输入移动的更精确追踪,请使用 UserInputService.TouchMoved

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

还请参阅:

参数

swipeDirection: Enum.SwipeDirection

Direction.SwipeDirection,表示用户滑动的方向。

numberOfTouches: number

涉及手势的触摸次数(例如手指)。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

触摸按钮事件触发,当用户在TouchEnabled设备上触摸他们的手指时。

无论用户是否触摸游戏世界或GUI 元素,此事件都会触发。如果您正在寻找只会触摸游戏世界时发生的事件,请使用UserInputService.TouchTapInWorld

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于这个事件只会在本地发生,它只能在 LocalScript 中使用。

参数

touchPositions: Array

Datatype.Vector2 对象,表示与点击手势有关的手指位置。

gameProcessedEvent: bool

指示游戏引擎是否内部观察到此输入并作出反应。 一般这会指向UI处理,因此如果从此输入触摸或单击了一个按钮,gameProcessedEvent将是true。 此也是对于通过ContextActionService连接的输入事件的情况。


代码示例

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

触摸世界中的事件触发,当用户在屏幕上的手指触摸/点击时。它是触摸世界中的用户触摸/点击时触发。

此事件可以用于确定用户是否点击屏幕,并且不是否点击 GUI 元素。如果用户点击 GUI 元素, UserInputService.TouchTap 将触发而不是触发在世界中。

要检查用户的设备是否触摸启用,并且触摸事件是否会触发,请参阅UserInputService.TouchEnabled

此事件仅发生在 Roblox 客户端窗口处于聚焦状态。例如,当窗口最小化时,输入不会被捕获。

由于它只能在本地发射,它只能用在 LocalScript 中。

还请参阅:

参数

position: Vector2

一个 Vector2 指示触摸位置。

processedByUI: bool

用户是否点击了一个图形用户界面元素。


代码示例

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

Class.UserInputService 窗口焦点释放事件触发,当 Roblox 客户端的窗口失焦 - 通常是在 Roblox 客户端被用户最小化时。

例如,下面的代码会每当 Roblox 客户端失焦时打印 “窗口焦点释放”


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

此事件可以与 UserInputService.WindowFocused 一起使用,以跟踪 Roblox 客户端是否正在主动关注用户的屏幕。

由于它只能在本地发射,因此它只能用在 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)
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

UserInputService 窗口焦点时,窗口焦点事件触发 - 通常是在 Roblox 客户端的窗口最大化/打开时发生。

例如,下面的代码会每当 Roblox 客户端获得焦点时打印 “窗口聚焦”


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

此事件可以与 UserInputService.WindowFocusReleased 一起使用,以跟踪 Roblox 客户端是否正在主动关注用户的屏幕。

由于这个事件只会在本地发生,它只能在 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)
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)