User Input Service
概要
屬性
MouseIcon:ContentId |
方法
CreateVirtualInput(target: Instance):Object |
GamepadSupports(gamepadNum: Enum.UserInputType,gamepadKeyCode: Enum.KeyCode):boolean |
GetGamepadConnected(gamepadNum: Enum.UserInputType):boolean |
GetGamepadState(gamepadNum: Enum.UserInputType):{InputObject} |
GetImageForKeyCode(keyCode: Enum.KeyCode):ContentId |
GetStringForKeyCode(keyCode: Enum.KeyCode,format: Enum.KeyCodeStringFormat):string |
GetSupportedGamepadKeyCodes(gamepadNum: Enum.UserInputType):{any} |
GetUserCFrame(type: Enum.UserCFrame):CFrame |
IsGamepadButtonDown(gamepadNum: Enum.UserInputType,gamepadKeyCode: Enum.KeyCode):boolean |
IsKeyDown(keyCode: Enum.KeyCode):boolean |
IsMouseButtonPressed(mouseButton: Enum.UserInputType):boolean |
IsNavigationGamepad(gamepadEnum: Enum.UserInputType):boolean |
SetNavigationGamepad(gamepadEnum: Enum.UserInputType,enabled: boolean):() |
活動
API 參考
屬性
Accelerometer Enabled
範例程式碼
使用加速度計移動球
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)
endModal Enabled
Mouse Icon
User Input Service. Mouse Icon:ContentId
範例程式碼
自訂滑鼠圖示
local UserInputService = game:GetService("UserInputService")
-- 為了將游標恢復到之前設定的樣子,需要將其保存到變數中
local savedCursor = nil
local function setTemporaryCursor(cursor: string)
-- 只有在當前沒有保存的游標時才更新保存的游標
if not savedCursor then
savedCursor = UserInputService.MouseIcon
end
UserInputService.MouseIcon = cursor
end
local function clearTemporaryCursor()
-- 只有在有保存的游標可以恢復時才恢復滑鼠游標
if savedCursor then
UserInputService.MouseIcon = savedCursor
-- 不要重複恢復相同的游標(可能會覆蓋其他腳本)
savedCursor = nil
end
end
setTemporaryCursor("http://www.roblox.com/asset?id=163023520")
print(UserInputService.MouseIcon)
clearTemporaryCursor()Mouse Icon Content
範例程式碼
自訂滑鼠圖示
local UserInputService = game:GetService("UserInputService")
-- 為了將游標恢復到之前設定的樣子,需要將其保存到變數中
local savedCursor = nil
local function setTemporaryCursor(cursor: string)
-- 只有在當前沒有保存的游標時才更新保存的游標
if not savedCursor then
savedCursor = UserInputService.MouseIcon
end
UserInputService.MouseIcon = cursor
end
local function clearTemporaryCursor()
-- 只有在有保存的游標可以恢復時才恢復滑鼠游標
if savedCursor then
UserInputService.MouseIcon = savedCursor
-- 不要重複恢復相同的游標(可能會覆蓋其他腳本)
savedCursor = nil
end
end
setTemporaryCursor("http://www.roblox.com/asset?id=163023520")
print(UserInputService.MouseIcon)
clearTemporaryCursor()Preferred Input
範例程式碼
首選輸入檢測
local UserInputService = game:GetService("UserInputService")
local function preferredInputChanged()
local preferredInput = UserInputService.PreferredInput
if preferredInput == Enum.PreferredInput.Touch then
-- 玩家在觸控設備上,且沒有其他輸入類型可用/連接
print("觸控")
elseif preferredInput == Enum.PreferredInput.Gamepad then
-- 玩家已連接或最近與遊戲手柄互動
print("遊戲手柄")
elseif preferredInput == Enum.PreferredInput.KeyboardAndMouse then
-- 玩家已連接或最近與鍵盤或滑鼠互動
print("鍵盤和滑鼠")
end
end
preferredInputChanged()
UserInputService:GetPropertyChangedSignal("PreferredInput"):Connect(function()
preferredInputChanged()
end)User Head C Frame
VR Enabled
方法
Create Virtual Input
Gamepad Supports
User Input Service: Gamepad Supports(
參數
返回
Get Device Acceleration
範例程式碼
輸出裝置加速度
local UserInputService = game:GetService("UserInputService")
if UserInputService.AccelerometerEnabled then
local acceleration = UserInputService:GetDeviceAcceleration().Position
print(acceleration)
else
warn("無法獲取裝置加速度,因為裝置沒有啟用的加速度計!")
endGet Device Gravity
範例程式碼
使用陀螺儀移動物體
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
-- 當陀螺儀檢測到變化時綁定事件
UserInputService.DeviceGravityChanged:Connect(function(accel)
-- 根據陀螺儀數據在世界中移動氣泡
bubble.Position = Vector3.new(-8 * accel.Position.X, 1.8, -8 * accel.Position.Z)
end)
endGet Device Rotation
Get Gamepad Connected
參數
返回
Get Gamepad State
參數
返回
Get Image For Key Code
參數
返回
ContentId
範例程式碼
UserInputService - 獲取 KeyCode 的圖像
local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappedIconImage = UserInputService:GetImageForKeyCode(key)
imageLabel.Image = mappedIconImageGet Last Input Type
範例程式碼
檢測最後輸入類型
local UserInputService = game:GetService("UserInputService")
if UserInputService:GetLastInputType() == Enum.UserInputType.Keyboard then
print("最近的輸入是鍵盤!")
endGet Mouse Buttons Pressed
返回
範例程式碼
檢查按下的滑鼠按鈕
local UserInputService = game:GetService("UserInputService")
UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
-- 返回按下的滑鼠按鈕的陣列
local buttonsPressed = UserInputService:GetMouseButtonsPressed()
local m1, m2 = false, false
for _, button in buttonsPressed do
if button.UserInputType == Enum.UserInputType.MouseButton1 then
print("MouseButton1 被按下!")
m1 = true
end
if button.UserInputType == Enum.UserInputType.MouseButton2 then
print("MouseButton2 被按下!")
m2 = true
end
if m1 and m2 then
print("兩個滑鼠按鈕都被按下!")
end
end
end)Get Mouse Delta
返回
範例程式碼
獲取滑鼠位移
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
local function onRenderStep()
local delta = UserInputService:GetMouseDelta()
if delta ~= Vector2.new(0, 0) then
print("滑鼠已移動", delta, "自上一步以來")
end
end
RunService:BindToRenderStep("MeasureMouseMovement", Enum.RenderPriority.Input.Value, onRenderStep)Get String For Key Code
參數
| 預設值:Default |
返回
Get Supported Gamepad Key Codes
參數
返回
Get User C Frame
Is Gamepad Button Down
User Input Service: Is Gamepad Button Down(
參數
返回
Is Mouse Button Pressed
參數
返回
參數
返回
Recenter User Head C Frame
User Input Service: Recenter User Head C Frame():()
返回
()
參數
返回
()
活動
Device Acceleration Changed
參數
範例程式碼
使用加速度計控制玩家
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local SENSITIVITY = 0.2
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local ready = true
local function changeAcceleration(acceleration)
if ready then
ready = false
local accel = acceleration.Position
if accel.Y >= SENSITIVITY then
humanoid.Jump = true
end
if accel.Z <= -SENSITIVITY then
humanoid:Move(Vector3.new(-1, 0, 0))
end
if accel.Z >= SENSITIVITY then
humanoid:Move(Vector3.new(1, 0, 0))
end
if accel.X <= -SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, 1))
end
if accel.X >= SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, -1))
end
task.wait(1)
ready = true
end
end
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceAccelerationChanged:Connect(changeAcceleration)
endDevice Gravity Changed
參數
範例程式碼
使用加速度計移動球
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)
endDevice Rotation Changed
參數
Gamepad Connected
參數
Gamepad Disconnected
參數
Input Began
參數
Input Changed
參數
Input Ended
參數
Jump Request
範例程式碼
禁用預設跳躍
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
local processJumpRequest = false
local COOLDOWN_TIME = 0.5
local function jumpRequest()
if processJumpRequest == false then
processJumpRequest = true
-- 處理自定義跳躍請求
print("跳躍請求!")
-- 在冷卻後重置防抖變數
task.wait(COOLDOWN_TIME)
processJumpRequest = false
end
end
UserInputService.JumpRequest:Connect(jumpRequest)Last Input Type Changed
參數
Pointer Action
Text Box Focused
參數
範例程式碼
聚焦和失去焦點時的文本框修改
local UserInputService = game:GetService("UserInputService")
local function textBoxFocused(textBox)
textBox.BackgroundTransparency = 0
end
local function textBoxFocusReleased(textBox)
textBox.BackgroundTransparency = 0.5
end
UserInputService.TextBoxFocused:Connect(textBoxFocused)
UserInputService.TextBoxFocusReleased:Connect(textBoxFocusReleased)Text Box Focus Released
參數
範例程式碼
聚焦和失去焦點時的文本框修改
local UserInputService = game:GetService("UserInputService")
local function textBoxFocused(textBox)
textBox.BackgroundTransparency = 0
end
local function textBoxFocusReleased(textBox)
textBox.BackgroundTransparency = 0.5
end
UserInputService.TextBoxFocused:Connect(textBoxFocused)
UserInputService.TextBoxFocusReleased:Connect(textBoxFocusReleased)Touch Drag
User Input Service. Touch Drag(
參數
Touch Ended
參數
Touch Long Press
User Input Service. Touch Long Press(
參數
Touch Moved
參數
Touch Pan
User Input Service. Touch Pan(
touch Positions:{any}, total Translation:Vector2, velocity:Vector2, state:Enum.UserInputState, game Processed Event:boolean
參數
Touch Pinch
User Input Service. Touch Pinch(
touch Positions:{any}, scale:number, velocity:number, state:Enum.UserInputState, game Processed Event:boolean
參數
Touch Rotate
User Input Service. Touch Rotate(
touch Positions:{any}, rotation:number, velocity:number, state:Enum.UserInputState, game Processed Event:boolean
參數
Touch Started
參數
Touch Swipe
User Input Service. Touch Swipe(
參數
Touch Tap
Touch Tap In World
User C Frame Changed
Window Focus Released
範例程式碼
視窗焦點離開腳本(LocalScript)
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local awayEvent = ReplicatedStorage:WaitForChild("AwayEvent")
local function focusGained()
awayEvent:FireServer(false)
end
local function focusReleased()
awayEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)窗口焦點離開腳本 (腳本)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local awayEvent = Instance.new("RemoteEvent")
awayEvent.Name = "AwayEvent"
awayEvent.Parent = ReplicatedStorage
local function manageForceField(player, away)
if away then
local forceField = Instance.new("ForceField")
forceField.Parent = player.Character
else
local forceField = player.Character:FindFirstChildOfClass("ForceField")
if forceField then
forceField:Destroy()
end
end
end
awayEvent.OnServerEvent:Connect(manageForceField)