UserInputService

顯示已棄用項目

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

無法建立
服務
未複製

UserInputService 是一種服務,可以偵測並捕捉不同類型的輸入可用在用戶設裝置上。

此服務的主要目的是允許體驗與多種可用輸入方式合作,例如遊戲控制器、觸摸屏幕和鍵盤。它允許一個 LocalScript 執行不同的操作,依據裝置,並最終提供最佳體驗給終端用戶。

一些使用此服務的使用例包括偵測使用者輸入,當使用者與GUI、工具和其他遊戲實例互動時。為了偵測使用者輸入,服務必須尋找服務事件。例如,服務可以偵測到使用者使用移動設備的螢幕使用 Class.UserInputService.TouchStart

此服務只適用於客戶端,因此只有在 LocalScriptModuleScriptLocalScript 所需時才會運行。 作為 1>Class.LocalScript1> 的客戶端,遊戲中的用戶只能偵測自己的輸入 - 而不是其他人的輸入。

也參閱 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 枚。預設值是 Enum.MouseBehavior.Default。

可以設置為三個值:

  1. 預設:滑鼠在使用者的螢幕上自由移動。
  2. 鎖定中心 : 鼠標鎖定,無法從使用者螢幕的中心移動。
  3. 鎖定目前位置 : 滑鼠鎖定,無法從位置移動,它的位置是使用者在屏幕上的時間的當前位置。

這個屬性的值不會影響事件追蹤鼠標運動的靈敏度。例如, GetMouseDelta 會返回相同的 Vector2 畫面位置,無論是否鎖定或能夠自由移動在用戶的畫面上。因結果,控制攝影機的指標腳

如果 GuiButtonModal 啟用,則 GuiButton.Visible 除非玩家的右鍵已停用。

注意,如果鼠標鎖定,UserInputService.InputChanged 仍會在玩家移動鼠標時發射,並且在 Delta 中通過。此外,如果玩家被從遊戲中踢出,則會強制解鎖鼠標。

作為 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 只有客戶端,此屬性只能在 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
平行讀取

滑鼠圖示 屬性決定使用的圖像。如果為空,將使用預設箭頭。而 ImageButtonTextButton 、1> Class.Seconds1> 或 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

唯讀
未複製
平行讀取

此屬性描述使用者目前的設備是否有可用的觸摸螢幕。

屬性是用來決定用戶的裝置是否具有觸摸屏幕,並且是否發生觸摸事觸發。如果 TouchEnabled 是真的,你可以使用 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 裝置啟用,您可以通過功能 such as UserInputService:GetUserCFrame() 與其位置和移動互動。您也可以使用 UserInputService.UserCFrameChanged 事件來反應 VR 裝置的移動。


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 的遊戲控制器的陣列。如果沒有控制器連接,此陣列將為空。此外,它只會返回連接遊戲控制器的鍵盤對象的陣列。例個體、實例,此事件將返回連接的 Gamepad1 對象,但不是鍵盤對物件。

舉例來說,下列代碼擷取連接的遊戲控制器並儲存在 連接的遊戲控制器 變量中。


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

要檢查特定遊戲控制器是否連接,請使用 UserInputService:GetGamepadConnected()

作為 UserInputService 只有客戶端,此功能只能在 LocalScript 中使用。

也看:


返回

一個集合 UserInputTypes 與用戶裝置連接的遊戲控制器。

範例程式碼

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 描述裝置目前的重力向量力。

重力量是由裝置的方向與實際世界的重力強度相對決定的。例個體、實例,如果裝置完全直立 (portrait),重力量是 Vector3.new(0, 0, -9.18)。如果裝置的左側指向下,重力量是 Vector3.new(

這個函數可能會用來啟用使用者的裝置在遊戲中影響或控制重力,或移動遊戲中的物件,例如球。

僅有啟用陀螺儀的裝置才會偵測到重力 - 例如行動裝置。

要檢查使用者的裝置是否有啟用的陀螺儀,請檢查 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

此功能會返回 InputObjectCFrame,描述裝置的當前旋轉向向量力。

這是用輸入對象發射。 位置 屬性的輸入對象是一個 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,此功能將返回 nil

作為 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

ень輸入型態 與遊戲控制器對應。


返回

一個表示所有可用輸入對象狀態的 InputObjects

GetImageForKeyCode

ContentId

此方法接受要求的 Enum.KeyCode 並且將連接的遊戲控制器 (限於 Xbox、PlayStation 和 Windows) 的圖像返回連接的遊戲控制器 (限於 Xbox 一個控制器)。這意味著如果連接控制器是一個 Xbox 控制器,用戶將看到 Xbox 資產。同樣地,

參數

keyCode: Enum.KeyCode

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 值來重複,以確定目前哪些鍵正在被按,並使用 Class.InputObject.KeyCode 值。

要檢查特定鍵是否被按下,請使用 UserInputService:IsKeyDown()

作為 UserInputService 只有客戶端,此功能只能在 LocalScript 中使用。


返回

一個用於鍵壓下現在正在按下的鍵的陣列。

範例程式碼

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

此函數會返回「enum.UserInputType」與用戶最近輸入相關的輸入。

舉例來說,如果使用者的上一個輸入按下空格鍵,Enum.UserInputType 將會返回 Keyboard。

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

此函數返回一個 InputObjects 對應目前按下的滑鼠按鈕。

這個功能追蹤的滑鼠按鈕包括:


<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 屬性鎖定時才會工作。如果沒有鎖定,則會返回 1> Datatype.Vector

客戶端的設定中決定的滑鼠靈敏度,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 在畫素相對於左上角的當前屏幕位置。這不包括 GUI 的預設。

如果鼠標指向器的位置是 offscreen 或玩家的裝置沒有滑鼠標,返回的值將會是未定義的。

作為 UserInputService 只有客戶端,此功能只能在 LocalScript 中使用。


返回

Datatype.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導航而啟用的陣列。此列表是由優先權순序為下降排序的優先權,因此可以以此為基礎來決定哪個陣列有權獲得導航控制。

連接的遊戲控制器是僅導航控制器控制導航按鈕的手把戲控制器。這對導航控制沒有影響。

由於 UserInputService 只是在客戶端,因此此功能只能在 LocalScript 中使用。

也看:


返回

一個用於GUI導航的UserInputTypes ,可以按優先權下降的順序使用。

GetStringForKeyCode

GetStringForKeyCode 返回代表用戶應該按下的鍵的字串,保留鍵盤的布局。對於需要一些修改者的鍵代碼,此功能會將鍵代碼返回鍵盤,而不是模組器。請參閱下面的範例,以獲得更多說明。

使用 Roblox 時,若使用者使用非 QWERTY 鍵盤結構,鍵盤代碼會與相當的 QWERTY 位置結合。


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

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>enum.keycode.at</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>enum.keycode.at</code></td>
<td><code>É</code></td>
</tr>
</tbody>
鑰匙碼返回值

遊戲控制器使用

GetStringForKeyCode() 返回最近連接的遊戲手柄的字串映射。如果控制器不支持,則會返回要求的鍵碼的預設字串轉換。

下面的例子顯示了您如何可以為 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>枚號碼按鈕</code></td>
<td><code>按鈕十字路口</code></td>
<td><code>按鈕A</code></td>
</tr>
<tr>
<td><code>枚號碼按鈕</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>枚號碼按鈕</code></td>
<td><code>按鈕三角形</code></td>
<td><code>按鈕Y</code></td>
</tr>
<tr>
<td><code>枚號碼按鈕 L1</code></td>
<td><code>ButtonL1</code></td>
<td><code>ButtonLB</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>枚號碼碼按鈕 R1</code></td>
<td><code>按鈕R1</code></td>
<td><code>按鈕RB</code></td>
</tr>
<tr>
<td><code>枚號碼碼按鈕 R2</code></td>
<td><code>按鈕 R2</code></td>
<td><code>按鈕RT</code></td>
</tr>
<tr>
<td><code>枚號碼碼按鈕 R3</code></td>
<td><code>按鈕R3</code></td>
<td><code>按鈕RS</code></td>
</tr>
<tr>
<td><code>枚號鍵碼按鈕開始</code></td>
<td><code>按鈕選項</code></td>
<td><code>按鈕開始</code></td>
</tr>
<tr>
<td><code>枚號.KeyCode.ButtonSelect</code></td>
<td><code>按鈕觸摸板</code> 和 <code>按鈕共享</code></td>
<td><code>按鈕選擇</code></td>
</tr>
</tbody>
鑰匙碼PlayStation 返回值Xbox 返回價值

鑰匙碼系統圖像

使用 Class.ImageLabel 在用戶界面上的用戶界面,如果使用 Class.ImageLabel 在用戶界面上的用戶界面,您可以使用以下傳統圖示。 但是,建議您使用 Class.UserInputService:GetImageForKeyCode()|GetImageForKeyCode() 作為更新的交叉平台方法來取回 Xbox 和 Play


<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>枚號碼按鈕</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>枚號碼按鈕</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>枚號碼按鈕</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>enum.keycode.DPadUp</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadUp.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/dpadUp.png</code></td>
</tr>
<tr>
<td><code>枚號碼代碼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>枚號.KeyCode.ButtonSelect</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxView.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxView.png</code></td>
</tr>
<tr>
<td><code>枚號鍵碼按鈕開始</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>枚號碼按鈕 L1</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>枚號碼碼按鈕 R1</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>枚號碼碼按鈕 R2</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>枚號碼碼按鈕 R3</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRS.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRS.png</code></td>
</tr>
<tr>
<td><code>enum.keycode.thumbstick1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLSDirectional.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxLSDirectional.png</code></td>
</tr>
<tr>
<td><code>枚數.KeyCode.Thumbstick2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRSDirectional.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRSDirectional.png</code></td>
</tr>
<tr>
<td><code>枚號.KeyCode.Backspace</code></td>
<td>
<img src="../../../assets/scripting/controls/backspace.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/backspace.png</code></td>
</tr>
<tr>
<td><code>枚列鑰匙代碼返回</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>枚號碼碼頭</code></td>
<td>
<img src="../../../assets/scripting/controls/apostrophe.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/apostrophe.png</code></td>
</tr>
<tr>
<td><code>enum.keycode.comma</code></td>
<td>
<img src="../../../assets/scripting/controls/comma.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/comma.png</code></td>
</tr>
<tr>
<td><code>枚號.KeyCode.Backquote</code></td>
<td>
<img src="../../../assets/scripting/controls/graveaccent.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/graveaccent.png</code></td>
</tr>
<tr>
<td><code>枚號.KeyCode.Period</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>枚號.KeyCode.Space</code></td>
<td>
<img src="../../../assets/scripting/controls/spacebar.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/spacebar.png</code></td>
</tr>
</tbody>
鑰匙碼圖像資產 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 按下,否則它將返回失敗。

有效的使用者輸入類型

指定的遊戲控制器應該是其中的一個 UserInputType 枚值:


<tr>
<td>枚數。UserInputType.Gamepad1-8</td>
</tr>
名稱

有效的鑰匙代碼

指定的按鈕應該是以下的 KeyCodes 枚值之一:


<tr>
<td>枚數.KeyCode.ButtonX</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonY</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonA</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonB</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonR1</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonL1</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonR2</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonL2</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonR3</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonL3</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonStart</td>
</tr>
<tr>
<td>枚數.KeyCode.ButtonSelect</td>
</tr>
<tr>
<td>枚數。鑰匙代碼。DPadLeft</td>
</tr>
<tr>
<td>枚數。鍵碼。DPadRight</td>
</tr>
<tr>
<td>枚數.KeyCode.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

鑰鍵的 Enum.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 按鈕,並且返回指示它是否目前按下的按鈕。

檢查鼠標按鈕依據 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

可以使用「UserInput/GetConnectedGamepads」取回所有連接的遊戲控制器。

由於 UserInputService 只是在客戶端,因此此功能只能在 LocalScript 中使用。

也看:

參數

gamepadEnum: Enum.UserInputType

指定遊戲控制器的 Enum.UserInputType


返回

是否指定的遊戲控制器是導航遊戲控制器。

RecenterUserHeadCFrame

void

這個函數將 VR 頭戴的 CFrame 重新設置到用戶使用的頭戴的目前方向。這意味著頭戴的目前方向已設置為 CFrame.new()

使用此功能將耳機 CFrame 移動到播放區域的中心,如果它看起來在一個奇怪的偏移值。

這會與 VRService 函數的相同, VRService:RecenterUserHeadCFrame()

由於 UserInputService 只是在客戶端,因此此功能只能在 LocalScript 中使用。


返回

void

範例程式碼

UserInputService:RecenterUserHeadCFrame

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

SetNavigationGamepad

void

SetNavigationGamepad 函數設置是否允許指定的 Enum.UserInputType 遊戲板可以移動 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

Class.InputObject ,包括 UserInputTypeAccelerometer ,以及 1>Class.InputObject.Position|Position1> ,顯示每個本地裝置軸的重力強度。


範例程式碼

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

Class.UserInputService.DeviceGravityChanged 事件發生時,當裝置的重力 Vector3 改變時。

裝置的重力ベクト表示裝置的 X、Y 和 Z 軸上的重力力。雖然重力不會改變,但在裝置旋轉和變更方向時,重力對每個軸的力量會變化。 對每個軸的力量的值是 -1 到 1 的單位範圍。

加速度計是尋找在大多數移動設備上的加速度計(速度變化)。

這個事件可以用來確定使用者裝置上重力的方向。這個方法可以用來模擬遊戲中使用者裝置上的重力,例如在遊戲中的對象(請參閱下面的範例)。

要檢查使用者的裝置是否有啟用的加速度計,請參閱 UserInputService.AccelerometerEnabled。如果裝置有加速度計,您可以使用 UserInputService:GetDeviceGravity() 函數來取得使用者裝置上的當前重力。

參數

gravity: InputObject

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

裝置旋轉變更事件會發生,當使用者旋轉一個具有陀螺儀的裝置。

陀螺儀是偵測方向和旋轉速度的移動設備的主要零件。

當追蹤設備的方向時,事件很有用,因為使用者旋轉設備時,如何改變設裝置的方向。要確定目前的設備旋轉,您可以使用 UserInputService:GetDeviceRotation() 函數。

要檢查使用者的裝置是否有啟用的陀螺儀,並且這個事件會發觸發,請參閱 UserInputService.GyroscopeEnabled

此事件只會在 Roblox 客戶端窗口位於專注模式時發生。例如,當窗口最小化時輸入將不會被捕捉。

參數

rotation: InputObject

提供關於裝置旋轉的資訊。InputObject.Position代表新旋轉位置的Vector3位置值,並代表1>Class.InputObj.Delta1>代表在4>Datatype.Vector34>位置的旋轉變更。

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 中發生,因此它只能在 Class.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 中發生,因此它只能在 Class.LocalScript 中使用。

也看:

參數

gamepadNum: Enum.UserInputType

枚數.UserInputType 的遊戲控制器。


InputBegan

輸入程式開始事件會在使用者開始互動以下人類電腦介面裝置 (滑鼠按鈕, 觸摸開始, 鍵盤按鈕, 等等) 時發生。

它可以用來追蹤用戶與用戶界面的互動開始,例如當使用者與 GUI 元素互動時,或遊戲控制器等。它不會捕捉滑鼠輪動。

這個事件可以與 UserInputService.InputChangedUserInputService.InputEnded 一起使用來跟蹤使用者輸入開始、變更和結束的時間。

此事件只會在 Roblox 客戶端窗口位於專注模式時發生。例如,當窗口最小化時輸入將不會被捕捉。

這個事件只在本地發生,因此它只能在 LocalScript 中使用。

參數

Class.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 中使用。

參數

Class.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 中使用。

參數

Class.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,以便跳躍玩家的角色。

這個事件可以用來追蹤玩家想要跳躍的時間。 而不是使用它來讓玩家跳躍,這個應該用來變更預設跳躍行為 - 例如停用跳躍。

舉例來說,下面的代碼會每次玩家發送跳躍請邀請時列出 "Jump"。


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 失焦時的名稱。


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事件發生,當客戶端點擊/點擊開始輸入文字時。這也會在 TextBox 中發生,通常是客戶端點擊/點擊文字框以開始輸入文字。這也會發生,如果 TextBox:CaptureFocus() 在輸入文字時專注。

舉例來說,下面的代碼會列出發生事件時 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 中使用。

也看:

參數

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

一個 Vector2 對象群,表示指定手勢的位置。

枚號.UserInputState 的手勢。

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

觸動事件發生,當使用者移動他們的手指到一個觸擦啟用的裝置。

這個事件可以用來決定使用者移動他們的手指時是否移動到 TouchEnabled 裝置的螢幕上。它可能有助於追蹤使用者是否在螢幕上移動他們的手指,以及使用者移動他們的手指的位置。

下面的代碼列印 "從" 上一個 Vector2 位置 "到" 新 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 中使用。

也看:

參數

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

觸摸板事件發生,當使用者拖曳至少一個手指在 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

一個 Vector2 對象群,表示觸摸操作中涉及的觸摸位置。(例如手指)

totalTranslation: Vector2

從開始到結束的鍋子手勢的尺寸 (以畫素計)。

velocity: Vector2

每秒鐘攝影機的速度 (以畫素計)。

枚號.UserInputState 的手勢。

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

一個 Vector2s ,表示觸摸手勢的屏幕位置,以幾何形式表示。

scale: number

開始到終止 (以幣計) 的輾磨程度。

velocity: number

每秒鐘的輕觸速度 (以畫素計)。

枚號.UserInputState 的手勢。

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

旋轉變更 (以度) 與變更時間 (以秒) 的比例。

枚號.UserInputState 的手勢。

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

TouchStarted 事件發生,當使用者將他們的手指放在 Class.UserInputService.TouchEnabled|TouchEnabled 裝置上,開始使用裝置的觸摸輸入。

這個事件可以用來確認使用者開始或停止使用者的設裝置的螢幕時間。它可以與 UserInputService.TouchEnded 配對,以確認使用者開始或停止使用者的螢幕。

觸摸輸入對象是在觸摸的整個生命時間都一樣的輸入對象。因此,比較 InputObjects 當它們是觸摸對象時是否是相同的指針。

要檢查使用者的裝置是否啟用觸控,並且觸控事件會否發觸發,請參閱 UserInputService.TouchEnabled

此事件只會在 Roblox 客戶端窗口位於專注模式時發生。例如,當窗口最小化時輸入將不會被捕捉。

這個事件只在本地發生,因此它只能在 LocalScript 中使用。

也看:

參數

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

觸摸輸入裝置發生觸摸/點擊時,觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生觸摸輸入裝置發生����

這個事件將在使用者碰觸/點擊遊戲世界或 GUI 元素時發生,無論使用者是否碰觸/點擊遊戲世界。如果您正在尋找僅在使用者碰觸/點擊遊戲世界時發生的事件,請使用 UserInputService.TouchTapInWorld

要檢查使用者的裝置是否啟用觸控,並且觸控事件會否發觸發,請參閱 UserInputService.TouchEnabled

此事件只會在 Roblox 客戶端窗口位於專注模式時發生。例如,當窗口最小化時輸入將不會被捕捉。

這個事件只在本地發生,因此它只能在 LocalScript 中使用。

參數

touchPositions: Array

一個 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 會發生而不是 TouchTapInWorld。

要檢查使用者的裝置是否啟用觸控,並且觸控事件會否發觸發,請參閱 UserInputService.TouchEnabled

此事件只會在 Roblox 客戶端窗口位於專注模式時發生。例如,當窗口最小化時輸入將不會被捕捉。

只有發射本地時才能使用,只能在 LocalScript 中使用。

也看:

參數

position: Vector2

Datatype.Vector2 指示觸摸位置。

processedByUI: bool

使用者是否點擊了一個 GUI 元素。


範例程式碼

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

Class.UserInputService 窗口專注事件發生,當 Roblox 客戶端的窗口獲得專注時 - 通常在 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)