UserInputService

แสดงที่เลิกใช้งานแล้ว

*เนื้อหานี้แปลโดยใช้ AI (เวอร์ชัน Beta) และอาจมีข้อผิดพลาด หากต้องการดูหน้านี้เป็นภาษาอังกฤษ ให้คลิกที่นี่

ไม่สามารถสร้าง
บริการ
ไม่ซ้ำ

UserInputService เป็นบริการที่ใช้ในการตรวจจับและจับภาพชนิดของอินพุตที่แตกต่างกันที่มีอยู่ในอุปกรณ์ของผู้ใช้

วัตถุประสงค์หลักของบริการนี้คือการอนุญาตให้ประสบการณ์ร่วมมือกับหลายรูปแบบของการใส่ข้อมูลที่มีอยู่ เช่น แท็บเล็ตเกม หน้าจอสัมผัส และแป้นพิมพ์มันอนุญาตให้ LocalScript ดำเนินการด้วยการกระทําที่แตกต่างกันขึ้นอยู่กับอุปกรณ์และในทางกลับกันให้ประสบการณ์ที่ดีที่สุดแก่ผู้ใช้ปลายทาง

การใช้บริการนี้บางอย่างรวมถึงการตรวจจับการใส่ข้อมูลของผู้ใช้เมื่อพวกเขาโต้ตอบกับ GUI เครื่องมือ และตัวอย่างเกมอื่น ๆเพื่อตรวจจับการใส่ข้อมูลของผู้ใช้ บริการจะต้องมองหาเหตุการณ์บริการตัวอย่างเช่นบริการสามารถตรวจจับเหตุการณ์เช่นเมื่อผู้ใช้แตะหน้าจออุปกรณ์เคลื่อนที่โดยใช้ UserInputService.TouchStarted หรือเชื่อมต่อคอนโซลเกมเช่นคอนโซล Xbox กับอุปกรณ์ของพวกเขาโดยใช้ UserInputService.GamepadConnected

เนื่องจากบริการนี้เป็นเฉพาะด้านไคลเอนต์เท่านั้น จะทำงานได้เฉพาะเมื่อใช้ใน LocalScript หรือ ModuleScript ที่จำเป็นต้องใช้โดย LocalScriptเนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ผู้ใช้ในเกมสามารถตรวจจับการใส่ของตนเองได้เท่านั้น - และไม่ใช่การใส่ของผู้อื่น

ดูเพิ่มเติม ContextActionService บริการที่ช่วยให้คุณผูกฟังก์ชันกับการใส่ข้อมูลของผู้ใช้หลายราย

ตัวอย่างโค้ด

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

UserInputService

-- We must get the UserInputService before we can use it
local UserInputService = game:GetService("UserInputService")
-- A sample function providing one usage of InputBegan
local function onInputBegan(input, _gameProcessed)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed!")
end
end
UserInputService.InputBegan:Connect(onInputBegan)

สรุป

คุณสมบัติ

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    อธิบายว่าอุปกรณ์ของผู้ใช้มีเซนเซอร์ความเร่งหรือไม่

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    อธิบายว่าอุปกรณ์ที่ใช้โดยผู้ใช้มี gamepad ที่ใช้งานได้หรือไม่

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    อธิบายว่าอุปกรณ์ของผู้ใช้มีเซนเซอร์ไจโรหรือไม่

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    อธิบายว่าอุปกรณ์ของผู้ใช้มีแป้นพิมพ์ที่ใช้งานได้หรือไม่

  • อ่านพร้อมๆ กัน

    กำหนดว่าเมาส์ของผู้ใช้สามารถเคลื่อนย้ายได้อย่างอิสระหรือถูกล็อค

  • ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    ขยายการออก delta (การเปลี่ยนแปลง) ของผู้ใช้ Mouse

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    อธิบายว่าอุปกรณ์ของผู้ใช้มีเมาส์ที่ใช้งานหรือไม่

  • MouseIcon:ContentId
    อ่านพร้อมๆ กัน

    ID เนื้อหาของภาพที่ใช้เป็นไอคอนเมาส์ของผู้ใช้

  • อ่านพร้อมๆ กัน

    กำหนดว่าไอคอน Mouse มองเห็นได้หรือไม่

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    กำหนดตำแหน่งของแป้นพิมพ์บนหน้าจอ

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    กำหนดขนาดของแป้นพิมพ์บนหน้าจอ

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    อธิบายว่าแป้นพิมพ์บนหน้าจอมีอยู่ในปัจจุบันบนหน้าจอของผู้ใช้หรือไม่

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    อธิบายว่าอุปกรณ์ปัจจุบันของผู้ใช้มีหน้าจอสัมผัสที่ใช้งานได้หรือไม่

  • อ่านอย่างเดียว
    ไม่ซ้ำ
    อ่านพร้อมๆ กัน

    เฮดเซ็ท

วิธีการ

อีเวนต์

  • ยิงเมื่อผู้ใช้ย้ายอุปกรณ์ที่มีเครื่องวัดความเร่ง ใช้เพื่อติดตามการเคลื่อนไหวอุปกรณ์ในโลกแบบจริงภายในเกม Roblox

  • ยิงเมื่อแรงโน้มถ่วงเปลี่ยนบนอุปกรณ์ที่มีเครื่องวัดความเร่งเปิดใช้งาน - เช่นอุปกรณ์เคลื่อนที่

  • ยิงเมื่อผู้ใช้หมุนอุปกรณ์ที่มีเครื่องวัดความเร่ง

  • จะเกิดไฟไหม้เมื่อ gamepad ถูกเชื่อมต่อกับไคลเอนต์ ส่ง "gamepadNum" ของ gamepad ที่เชื่อมต่อ

  • จะเกิดไฟไหม้เมื่อ gamepad ถูกถอดจากไคลเอนต์ ส่งผ่าน Enum.UserInputType ของ gamepad ที่ถูกถอดออก

  • InputBegan(input : InputObject,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้เริ่มโต้ตอบผ่านอุปกรณ์อินเทอร์เฟซมนุษย์-คอมพิวเตอร์ - เช่นเมาส์หรือแผ่นเกม

  • InputChanged(input : InputObject,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้เปลี่ยนวิธีการโต้ตอบผ่านอุปกรณ์อินเทอร์เฟซมนุษย์-คอมพิวเตอร์

  • InputEnded(input : InputObject,gameProcessedEvent : boolean):RBXScriptSignal

    ไฟเมื่อผู้ใช้หยุดโต้ตอบผ่านอุปกรณ์อินเทอร์เฟซมนุษย์-คอมพิวเตอร์

  • ไฟไหม้เมื่อไรก็ตามที่ไคลเอนต์ส่งคำขอให้ตัวละครของพวกเขากระโดด

  • จะเกิดไฟไหม้เมื่อ Enum.UserInputType ของไคลเอนต์เปลี่ยนแปลง

  • PointerAction(wheel : number,pan : Vector2,pinch : number,gameProcessedEvent : boolean):RBXScriptSignal

    เกิดไฟเมื่อผู้ใช้ดำเนินการตามเมาส์ที่เฉพาะเจาะจง (ล้อ, บีบ, แพน)

  • ยิงเมื่อไคลเอนต์สูญเสียการโฟกัสบน TextBox

  • ยิงเมื่อไคลเอนต์มุ่งเน้นไปที่ TextBox

  • TouchDrag(dragDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
  • TouchEnded(touch : InputObject,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้ปล่อยนิ้วออกจากหน้าจอบนอุปกรณ์ที่เปิดใช้งานสัมผัส - เช่นหน้าจอของอุปกรณ์เคลื่อนที่

  • TouchLongPress(touchPositions : Array,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้กดนิ้วอย่างน้อยหนึ่งนิ้วเป็นเวลาสั้นๆ ในตำแหน่งหน้าจอเดียวกันบนอุปกรณ์ที่เปิดใช้งานการสัมผัส - เช่นหน้าจอของอุปกรณ์เคลื่อนที่

  • TouchMoved(touch : InputObject,gameProcessedEvent : boolean):RBXScriptSignal

    จะเกิดไฟไหม้เมื่อผู้ใช้ย้ายนิ้วบนอุปกรณ์ TouchEnabled เช่นแท็บเล็ตหรือสมาร์ทโฟน

  • TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้ลากนิ้วอย่างน้อยหนึ่งนิ้วบนอุปกรณ์ TouchEnabled - เช่นหน้าจอของอุปกรณ์เคลื่อนที่

  • TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้บีบนิ้วบนอุปกรณ์ TouchEnabled - เช่นหน้าจอของอุปกรณ์เคลื่อนที่

  • TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal

    จะเกิดไฟไหม้เมื่อผู้ใช้หมุนนิ้วสองนิ้วบนอุปกรณ์ TouchEnabled - เช่นหน้าจอของอุปกรณ์เคลื่อนที่

  • TouchStarted(touch : InputObject,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้วางนิ้วบนอุปกรณ์ที่เปิดใช้งานการสัมผัส - เช่นหน้าจอของ Apple iPad หรือ iPhone หรือโทรศัพท์ Android ของ Google

  • TouchSwipe(swipeDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal

    ไฟไหม้บนอุปกรณ์ TouchEnabled เมื่อผู้ใช้วางนิ้วลงบนหน้าจอแล้วกวาดไปทั่วหน้าจอและยกนิ้วออกด้วยความเร็วในการเคลื่อนที่บางอย่าง

  • TouchTap(touchPositions : Array,gameProcessedEvent : boolean):RBXScriptSignal

    ยิงเมื่อผู้ใช้แตะนิ้วบนอุปกรณ์ TouchEnabled - เช่นหน้าจอของอุปกรณ์เคลื่อนที่

  • TouchTapInWorld(position : Vector2,processedByUI : boolean):RBXScriptSignal

    จะเกิดไฟไหม้เมื่อผู้ใช้แตะโลกเกมบนอุปกรณ์ TouchEnabled - เช่นหน้าจอของอุปกรณ์เคลื่อนที่

  • เกิดไฟไหม้เมื่อหน้าต่างของไคลเอนต์ Roblox สูญเสียการโฟกัสบนหน้าจอของผู้ใช้

  • เกิดไฟไหม้เมื่อหน้าต่างของไคลเอนต์ Roblox ได้รับความสนใจบนหน้าจอของผู้ใช้

คุณสมบัติ

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

ตัวอย่างโค้ด

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

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

Move a Ball using the Accelerometer

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

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

GamepadEnabled

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายว่าอุปกรณ์ที่ใช้โดยผู้ใช้มี gamepad ที่ใช้งานได้หรือไม่หาก gamepads มีอยู่คุณสามารถใช้ UserInputService:GetConnectedGamepads() เพื่อดูรายการ gamepads ที่เชื่อมต่อ

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

ตัวอย่างโค้ด

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

How to Set the Active Gamepad for Input

local UserInputService = game:GetService("UserInputService")
local function getActiveGamepad()
local activeGamepad = nil
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for _, gamepad in connectedGamepads do
if activeGamepad == nil or gamepad.Value < activeGamepad.Value then
activeGamepad = gamepad
end
end
end
if activeGamepad == nil then -- Nothing is connected; set up for "Gamepad1"
activeGamepad = Enum.UserInputType.Gamepad1
end
return activeGamepad
end
if UserInputService.GamepadEnabled then
local activeGamepad = getActiveGamepad()
print(activeGamepad)
end

GyroscopeEnabled

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายว่าอุปกรณ์ของผู้ใช้มีเครื่องวัดความเร่งหรือไม่

ไจโรสโคปเป็นส่วนประกอบที่พบในอุปกรณ์เคลื่อนที่ส่วนใหญ่ที่ตรวจจับการหมุนและความเร็วในการหมุน

หากอุปกรณ์ของผู้ใช้มีเครื่องวัดความเร่ง คุณสามารถใช้รวมมันเข้ากับเกมของคุณโดยใช้ฟังก์ชัน UserInputService:GetDeviceRotation() และอีเวนต์ UserInputService.DeviceRotationChanged


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

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript

ตัวอย่างโค้ด

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

KeyboardEnabled

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายว่าอุปกรณ์ของผู้ใช้มีแป้นพิมพ์ที่ใช้งานได้หรือไม่คุณสมบัตินี้คือ true เมื่ออุปกรณ์ของผู้ใช้มีแป้นพิมพ์ที่ใช้งานได้ และ false เมื่อไม่มี

สามารถใช้เพื่อตรวจสอบว่าผู้ใช้มีแป้นพิมพ์ที่ใช้งานได้หรือไม่ - ซึ่งอาจเป็นสิ่งสำคัญหากคุณต้องการตรวจสอบว่าคุณสามารถใช้ UserInputService:IsKeyDown() หรือ UserInputService:GetKeysPressed() เพื่อตรวจสอบการใส่ข้อมูลบนแป้นพิมพ์ได้

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript

ตัวอย่างโค้ด

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

Check if Keyboard is Enabled

local UserInputService = game:GetService("UserInputService")
if UserInputService.KeyboardEnabled then
print("The user's device has an available keyboard!")
else
print("The user's device does not have an available keyboard!")
end

MouseBehavior

อ่านพร้อมๆ กัน

คุณสมบัตินี้กำหนดวิธีที่เมาส์ของผู้ใช้ทำงานตาม enum Enum.MouseBehavior ได้ สามารถตั้งค่าเป็นสามค่า:

  • Enum.MouseBehavior.Default — เมาส์เคลื่อนไหวได้อย่างอิสระรอบหน้าจอของผู้ใช้
  • Enum.MouseBehavior.LockCenter — เมาส์ถูกล็อคและไม่สามารถย้ายจากศูนย์กลางของหน้าจอผู้ใช้ได้
  • Enum.MouseBehavior.LockCurrentPosition — เมาส์ถูกล็อคและไม่สามารถย้ายจากตำแหน่งปัจจุบันบนหน้าจอของผู้ใช้ในเวลาที่ล็อคได้

ค่าของคุณสมบัตินี้ไม่ส่งผลต่อความไวของการติดตามการเคลื่อนไหวของเมาส์ในการติดตามเหตุการณ์ตัวอย่างเช่น GetMouseDelta ส่งคืนตำแหน่งหน้าจอเดียวกัน Vector2 ในพิกเซลไม่ว่าเมาส์จะถูกล็อคหรือสามารถเคลื่อนที่ได้อย่างอิสระรอบหน้าจอของผู้ใช้ผลที่ตามมาคือสคริปต์เริ่มต้นเช่นสคริปต์ที่ควบคุมกล้องจะไม่ได้รับผลกระทบจากคุณสมบัตินี้

คุณสมบัตินี้จะถูกแทนที่หาก GuiButton ที่มี Modal เปิดใช้งานอยู่เป็น GuiButton.Visible ยกเว้นหากปุ่มเมาส์ขวาของผู้เล่นลง

โปรดทราบว่าหากเมาส์ถูกล็อค UserInputService.InputChanged จะยังคงยิงเมื่อผู้เล่นย้ายเมาส์และจะผ่านเดลต้าที่เมาส์พยายามย้ายไปนอกจากนี้หากผู้เล่นถูกไล่ออกจากเกม เมาส์จะถูกปลดล็อกอย่างถาวร

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript

ตัวอย่างโค้ด

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

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

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

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

Create a Binoculars Script

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

MouseDeltaSensitivity

ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้กำหนดความไวของ Mouse ของผู้ใช้

ความไวกำหนดขอบเขตที่การเคลื่อนไหวของเมาส์จริงจะแปลเป็นการเคลื่อนไหวของเมาส์ในเกมสิ่งนี้สามารถใช้เพื่อปรับเปลี่ยนวิธีการติดตามการเคลื่อนไหวของเหตุการณ์ที่ไวที่เกี่ยวข้องกับการเคลื่อนไหวของเมาส์, เช่น GetMouseDelta , กับการเคลื่อนไหวของเมาส์

คุณสมบัตินี้ไม่ส่งผลต่อการเคลื่อนไหวของไอคอนเมาส์นอกจากนี้ยังไม่ส่งผลต่อการตั้งค่าความไวของกล้อง ความไวของกล้อง ที่พบในแท็บ การตั้งค่า ของเมนู การตั้งค่าของลูกค้า ซึ่งยังปรับความไวของการติดตามการเคลื่อนไหวของเหตุการณ์ด้วย

คุณสมบัตินี้มีค่าสูงสุดคือ 10 และค่าต่ำสุดคือ 0มูลค่าที่ต่ำกว่าตรงกับความไวต่ำกว่าและมูลค่าที่สูงกว่าตรงกับความไวสูงกว่า

เมื่อความไวเป็น 0 อีเวนต์ที่ติดตามการเคลื่อนไหวของเมาส์จะยังคงยิง แต่พารามิเตอร์และคุณสมบัติทั้งหมดที่ระบุถึงการเปลี่ยนแปลงในตำแหน่งเมาส์จะกลับมา Vector2.new() หรือ Vector3.new() ในกรณีของ InputObject.Deltaตัวอย่างเช่น GetMouseDelta จะส่งกลับเสมอ (0, 0)

ตัวอย่างโค้ด

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

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

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

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

Create a Binoculars Script

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end

MouseEnabled

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายว่าอุปกรณ์ของผู้ใช้มีเมาส์ที่ใช้งานหรือไม่คุณสมบัตินี้คือ true เมื่ออุปกรณ์ของผู้ใช้มีเมาส์ที่ใช้งานได้ และ false เมื่อไม่มี


local UserInputService = game:GetService("UserInputService")
if UserInputService.MouseEnabled then
print("The user's device has an available mouse!")
else
print("The user's device does not have an available mouse!")
end

เป็นสิ่งสำคัญที่ต้องตรวจสอบนี้ก่อนที่จะใช้ฟังก์ชันเมาส์ UserInputService เช่น UserInputService:GetMouseLocation()

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

ตัวอย่างโค้ด

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

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

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

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

Create a Binoculars Script

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end

MouseIcon

ContentId
อ่านพร้อมๆ กัน

คุณสมบัติ MouseIcon กำหนดภาพที่ใช้เป็นตัวชี้หากว่างเปล่าจะใช้ลูกศรเริ่มต้นในขณะที่เคอร์เซอร์ลอยอยู่เหนือวัตถุ UI บางอย่างเช่น ImageButton , TextButton , TextBox หรือ ProximityPrompt รูปภาพนี้จะถูกแทนที่และถูกเพิกเฉยชั่วคราว

เพื่อซ่อนเคอร์เซอร์โดยสิ้นเชิง ทำ ไม่ ใช้ภาพโปร่งใส แทนที่จะตั้ง UserInputService.MouseIconEnabled เป็น false

ตัวอย่างโค้ด

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

UserInputService.MouseIcon

local UserInputService = game:GetService("UserInputService")
-- In order to restore the cursor to what it was set to previously, it will need to be saved to a variable
local savedCursor = nil
local function setTemporaryCursor(cursor: string)
-- Only update the saved cursor if it's not currently saved
if not savedCursor then
savedCursor = UserInputService.MouseIcon
end
UserInputService.MouseIcon = cursor
end
local function clearTemporaryCursor()
-- Only restore the mouse cursor if there's a saved cursor to restore
if savedCursor then
UserInputService.MouseIcon = savedCursor
-- Don't restore the same cursor twice (might overwrite another script)
savedCursor = nil
end
end
setTemporaryCursor("http://www.roblox.com/asset?id=163023520")
print(UserInputService.MouseIcon)
clearTemporaryCursor()
print(UserInputService.MouseIcon)

MouseIconEnabled

อ่านพร้อมๆ กัน

คุณสมบัตินี้กำหนดว่าไอคอน Mouse จะปรากฏเมื่อ true ไอคอนของเมาส์มองเห็นได้ เมื่อ false ไม่ได้

ตัวอย่างเช่น ส่วนของโค้ดด้านล่างซ่อนไอคอนของเมาส์


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

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript

ตัวอย่างโค้ด

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

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

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

Hide Mouse During Keyboard Input

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

OnScreenKeyboardPosition

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายตำแหน่งของแป้นพิมพ์บนหน้าจอในพิกเซล ตำแหน่งของแป้นพิมพ์คือ Vector2.new(0, 0) เมื่อไม่สามารถมองเห็นได้

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript หรือ Script ที่ตั้งค่า RunContext เป็น Enum.RunContext.Client

ดูเพิ่มเติม OnScreenKeyboardVisible และ OnScreenKeyboardSize .

ตัวอย่างโค้ด

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

UserInputService.OnScreenKeyboardPosition

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

OnScreenKeyboardSize

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายขนาดของแป้นพิมพ์บนหน้าจอในพิกเซล ขนาดแป้นพิมพ์คือ Vector2.new(0, 0) เมื่อไม่สามารถมองเห็นได้

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript หรือ Script ที่ตั้งค่า RunContext เป็น Enum.RunContext.Client

ดูเพิ่มเติม OnScreenKeyboardVisible และ OnScreenKeyboardPosition .

OnScreenKeyboardVisible

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายว่าแป้นพิมพ์บนหน้าจอมีอยู่ในปัจจุบันบนหน้าจอของผู้ใช้หรือไม่

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript หรือ Script ที่ตั้งค่า RunContext เป็น Enum.RunContext.Client

ดูเพิ่มเติม OnScreenKeyboardSize และ OnScreenKeyboardPosition .

TouchEnabled

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายว่าอุปกรณ์ปัจจุบันของผู้ใช้มีหน้าจอสัมผัสที่ใช้งานได้หรือไม่

คุณสมบัติถูกใช้เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีหน้าจอสัมผัสหรือไม่ และดังนั้นหากเหตุการณ์แตะจะเกิดขึ้นหาก TouchEnabled เป็นจริง คุณสามารถใช้อีเวนต์ของ UserInputService เช่น UserInputService.TouchStarted และ UserInputService.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

ดูเพิ่ม:

ตัวอย่างโค้ด

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

VREnabled

อ่านอย่างเดียว
ไม่ซ้ำ
อ่านพร้อมๆ กัน

คุณสมบัตินี้อธิบายว่าผู้ใช้กำลังใช้อุปกรณ์เสมือนจริง (VR) หรือไม่

หากอุปกรณ์ VR เปิดใช้งานแล้ว คุณสามารถโต้ตอบกับตำแหน่งและการเคลื่อนไหวของมันผ่านฟังก์ชันเช่น UserInputService:GetUserCFrame()คุณยังสามารถตอบสนองต่อการเคลื่อนไหวของอุปกรณ์ VR โดยใช้เหตุการณ์ UserInputService.UserCFrameChanged


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

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น คุณสมบัตินี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

ตัวอย่างโค้ด

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

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

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

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

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

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

VR Head Tracking

local VRService = game:GetService("VRService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local function TrackHead(inputType, value)
if inputType == Enum.UserCFrame.Head then
head.CFrame = value
end
end
if VRService.VREnabled then
-- Set the initial CFrame
head.CFrame = VRService:GetUserCFrame(Enum.UserCFrame.Head)
-- Track VR headset movement and mirror for character's head
VRService.UserCFrameChanged:Connect(TrackHead)
end

วิธีการ

GamepadSupports

ฟังก์ชันนี้จะคืนว่า gamepad ที่ให้ไว้ Enum.UserInputType สนับสนุนปุ่มที่ตรงกับที่ให้ไว้ Enum.KeyCode หรือไม่ฟังก์ชันนี้ใช้เพื่อตรวจสอบการใส่เกมแพดที่ถูกต้อง

เพื่อกำหนดว่า gamepad ใด Enum.UserInputType ได้รับการเชื่อมต่อแล้วใช้ UserInputService:GetConnectedGamepads()

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

gamepadNum: Enum.UserInputType

The Enum.UserInputType ของ gamepad

ค่าเริ่มต้น: ""
gamepadKeyCode: Enum.KeyCode

The Enum.KeyCode ของปุ่มในคำถาม

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ว่า gamepad ที่ให้มาสนับสนุนปุ่มที่ตรงกับปุ่มที่ให้ไว้ Enum.KeyCode หรือไม่

ตัวอย่างโค้ด

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

Binding Functions to Gamepad Controls

local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local controller = Enum.UserInputType.Gamepad1
local buttonX = Enum.KeyCode.ButtonX
local function isSupported(gamepad, keycode)
return UserInputService:GamepadSupports(gamepad, keycode)
end
local function action()
print("Action")
end
if isSupported(controller, buttonX) then
ContextActionService:BindAction("sample action", action, false, buttonX)
end

GetConnectedGamepads

ฟังก์ชันนี้ส่งคืนคอลเลกชันของแผ่นเกม Enum.UserInputType ที่เชื่อมต่ออยู่ในปัจจุบันหากไม่มีเกมแพดถูกเชื่อมต่อ ตัวเรียงนี้จะว่างเปล่านอกจากนี้ยังคืนวัตถุ UserInputType อินสแตนซ์อีเวนต์นี้จะคืนวัตถุ Gamepad1 ที่เชื่อมต่อ แต่ไม่ใช่วัตถุแป้นพิมพ์

ตัวอย่างเช่น ชิ้นส่วนโค้ดต่อไปนี้ดึง gamepads ที่เชื่อมต่อและเก็บไว้ในตัวแปรชื่อ connectedGamepads


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

เพื่อตรวจสอบว่าเกมแพดเฉพาะถูกเชื่อมต่อหรือไม่ใช้ UserInputService:GetGamepadConnected()

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:


ส่งค่ากลับ

ชุดของ UserInputTypes ที่ตรงกับแผ่นเกมที่เชื่อมต่อกับอุปกรณ์ของผู้ใช้

ตัวอย่างโค้ด

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

How to Set the Active Gamepad for Input

local UserInputService = game:GetService("UserInputService")
local function getActiveGamepad()
local activeGamepad = nil
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for _, gamepad in connectedGamepads do
if activeGamepad == nil or gamepad.Value < activeGamepad.Value then
activeGamepad = gamepad
end
end
end
if activeGamepad == nil then -- Nothing is connected; set up for "Gamepad1"
activeGamepad = Enum.UserInputType.Gamepad1
end
return activeGamepad
end
if UserInputService.GamepadEnabled then
local activeGamepad = getActiveGamepad()
print(activeGamepad)
end

GetDeviceAcceleration

ฟังก์ชัน GetDeviceAcceleration กำหนดการเร่งความเร็วปัจจุบันของอุปกรณ์ของผู้ใช้มันส่งคืน InputObject ที่อธิบายการเร่งความเร็วปัจจุบันของอุปกรณ์

เพื่อให้สิ่งนี้ทำงานได้ อุปกรณ์ของผู้ใช้จะต้องมีเครื่องวัดความเร่งเปิดใช้งานเพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีเครื่องวัดความเร่งเปิดใช้งานหรือไม่ คุณสามารถตรวจสอบคุณสมบัติ UserInputService.AccelerometerEnabled ได้

หากต้องการติดตามการเปลี่ยนแปลงการเร่งความเร็วของอุปกรณ์ผู้ใช้แทน คุณสามารถใช้เหตุการณ์ UserInputService.DeviceAccelerationChanged

เนื่องจากมันจะยิงท้องถิ่นเท่านั้น จึงสามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

ตัวอย่างโค้ด

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

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

Print Device Acceleration

local UserInputService = game:GetService("UserInputService")
local accelerometerEnabled = UserInputService.AccelerometerEnabled
if accelerometerEnabled then
local acceleration = UserInputService:GetDeviceAcceleration().Position
print(acceleration)
else
print("Cannot get device acceleration because device does not have an enabled accelerometer!")
end

GetDeviceGravity

ฟังก์ชันนี้ส่งคืน InputObject ที่อธิบายเวกเตอร์แรงโน้มถ่วงปัจจุบันของอุปกรณ์

เวกเตอร์แรงโน้มถ่วงจะถูกกำหนดโดยการจัดตำแหน่งของอุปกรณ์เมื่อเทียบกับแรงโน้มถ่วงในโลกแบบจริงตัวอย่างเช่น หากอุปกรณ์ยืนตัวตรง (ภาพวาด) เวกเตอร์แรงโน้มถ่วงจะเป็น Vector3.new(0, 0, -9.18)หากด้านซ้ายของอุปกรณ์ชี้ลง เวกเตอร์จะเป็น Vector3.new(9.81, 0, 0)สุดท้าย หากด้านหลังของอุปกรณ์ชี้ลง เวกเตอร์จะเป็น Vector3.new(0, -9.81, 0)

ฟังก์ชันนี้อาจถูกใช้เพื่อเปิดใช้งานอุปกรณ์ของผู้ใช้ที่จะส่งผลกระทบหรือควบคุมแรงโน้มถ่วงภายในเกมหรือย้ายวัตถุในเกมเช่นลูกบอล

แรงโน้มถ่วงจะถูกติดตามเฉพาะสำหรับผู้เล่นที่ใช้อุปกรณ์ที่มีเซนเซอร์ไจโรสควบคุม - เช่นอุปกรณ์เคลื่อนที่

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีการเปิดใช้งานเครื่องวัดความเร่งหรือไม่ ตรวจสอบค่าของ UserInputService.GyroscopeEnabledหากอุปกรณ์มีการเปิดใช้งานไจโรสโคปคุณสามารถใช้เหตุการณ์ UserInputService.DeviceGravityChanged เพื่อติดตามเมื่อแรงโน้มถ่วงบนอุปกรณ์ของผู้ใช้เปลี่ยนไป

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

ตัวอย่างโค้ด

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

Moving Objects with the Gyroscope

local UserInputService = game:GetService("UserInputService")
local bubble = script.Parent:WaitForChild("Bubble")
local camera = workspace.CurrentCamera
camera.CameraType = Enum.CameraType.Scriptable
camera.CFrame = CFrame.new(0, 20, 0) * CFrame.Angles(-math.pi / 2, 0, 0)
if UserInputService.GyroscopeEnabled then
-- Bind event to when gyroscope detects change
UserInputService.DeviceGravityChanged:Connect(function(accel)
-- Move the bubble in the world based on the gyroscope data
bubble.Position = Vector3.new(-8 * accel.Position.X, 1.8, -8 * accel.Position.Z)
end)
end

GetDeviceRotation

ฟังก์ชันนี้จะคืน InputObject และ CFrame อธิบายเวกเตอร์การหมุนปัจจุบันของอุปกรณ์

นี้ถูกยิงด้วย InputObjectคุณสมบัติ ตำแหน่ง ของวัตถุอินพุตเป็น Enum.InputType.Gyroscope ที่ติดตามการหมุนทั้งหมดในแต่ละแกนอุปกรณ์ท้องถิ่น

การหมุนอุปกรณ์สามารถติดตามได้เฉพาะในอุปกรณ์ที่มี gyroscope เท่านั้น

เนื่องจากฟังก์ชันนี้จะเรียกใช้ท้องถิ่นจึงสามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

tuple ที่มีสองคุณสมบัติ:

  1. คุณสมบัติ delta อธิบายปริมาณการหมุนที่เกิดขึ้นล่าสุด
  2. CFrame คือการหมุนปัจจุบันของอุปกรณ์เมื่อเทียบกับกรอบอ้างอิงเริ่มต้น

ตัวอย่างโค้ด

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

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

Print Device Rotation

local UserInputService = game:GetService("UserInputService")
local gyroEnabled = UserInputService:GyroscopeEnabled()
if gyroEnabled then
local _inputObj, cframe = UserInputService:GetDeviceRotation()
print("CFrame: {", cframe, "}")
else
print("Cannot get device rotation because device does not have an enabled gyroscope!")
end

GetFocusedTextBox

ฟังก์ชันนี้จะคืน TextBox ที่ลูกค้ากําลังมุ่งเน้นอยู่ในปัจจุบันA TextBox สามารถเลือกได้ด้วยตนเองโดยผู้ใช้หรือสามารถบังคับให้เลือกโดยใช้ฟังก์ชัน TextBox:CaptureFocus()หากไม่มี TextBox ถูกเลือกฟังก์ชันนี้จะคืน nil

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่มเติม

ส่งค่ากลับ

GetGamepadConnected

ฟังก์ชันนี้จะคืนว่าเกมแพดที่มี Enum.UserInputType ที่กำหนดเชื่อมต่อกับไคลเอนต์หรือไม่

สิ่งนี้สามารถใช้เพื่อตรวจสอบว่าเกมแพดเฉพาะ เช่น 'Gamepad1' ได้เชื่อมต่อกับอุปกรณ์ของไคลเอนต์หรือไม่

เพื่อดูรายการของ gamepad ทั้งหมดที่เชื่อมต่อใช้ UserInputService:GetConnectedGamepads()

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

gamepadNum: Enum.UserInputType

The Enum.UserInputType ของ gamepad ในคำถาม

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ว่าคอนโซลเกมที่เชื่อมโยงกับ Enum.UserInputType ถูกเชื่อมต่อหรือไม่

ตัวอย่างโค้ด

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

Check Whether a Gamepad is Connected

local UserInputService = game:GetService("UserInputService")
local isConnected = UserInputService:GetGamepadConnected(Enum.UserInputType.Gamepad1)
if isConnected then
print("Gamepad1 is connected to the client")
else
print("Gamepad1 is not connected to the client")
end

GetGamepadState

ฟังก์ชันนี้ส่งคืนคอลเลกชันของ InputObjects สําหรับการใส่ทั้งหมดที่มีอยู่ในเกมแพดที่กำหนด Enum.UserInputType แทนสถานะการรับสุดท้ายของแต่ละอินพุต

เพื่อค้นหา UserInputTypes ของเกมแพดที่เชื่อมต่อกันใช้ UserInputService:GetConnectedGamepads()

เนื่องจากฟังก์ชันนี้จะเปิดใช้งานเฉพาะในท้องถิ่นเท่านั้น จึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

gamepadNum: Enum.UserInputType

The Enum.UserInputType ที่ตรงกับเกมแพดในคำถาม

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ชุดของ InputObjects ที่แทนสถานะปัจจุบันของการใส่ทั้งหมดที่มีอยู่สำหรับแผ่นเกมที่กำหนด

GetImageForKeyCode

ContentId

วิธีนี้ใช้ Enum.KeyCode ที่ร้องขอและส่งภาพที่เกี่ยวข้องกับอุปกรณ์เกมแพดที่เชื่อมต่ออยู่ในขณะนี้ (จํากัดเฉพาะ Xbox, PlayStation และ Windows)ซึ่งหมายความว่าหากคอนโทรลเลอร์ที่เชื่อมต่อเป็นคอนโทรลเลอร์ Xbox One ผู้ใช้จะเห็นสินทรัพย์ของ Xboxเช่นเดียวกันหากอุปกรณ์ที่เชื่อมต่อเป็นคอนโทรลเลอร์ของ PlayStation ผู้ใช้จะเห็นสินทรัพย์ของ PlayStationหากต้องการใช้สินทรัพย์ที่กําหนดเอง ดู GetStringForKeyCode()

พารามิเตอร์

keyCode: Enum.KeyCode

The Enum.KeyCode สำหรับการดึงภาพที่เกี่ยวข้อง

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ContentId

รหัสทรัพยากรภาพที่ส่งคืน

ตัวอย่างโค้ด

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

UserInputService - Get Image For KeyCode

local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappedIconImage = UserInputService:GetImageForKeyCode(key)
imageLabel.Image = mappedIconImage

GetKeysPressed

ฟังก์ชันนี้ส่งคืนคอลเลกชันของ InputObjects ที่เกี่ยวข้องกับแป้นที่กดอยู่ในขณะนี้

ค่าตัวนี้สามารถถูกนำไปผ่านเพื่อกำหนดว่าแป้นใดกำลังถูกกดอยู่ในขณะนี้โดยใช้ค่า InputObject.KeyCode เหล่านี้

เพื่อตรวจสอบว่ากุญแจที่เฉพาะเจาะจงถูกกดหรือไม่ใช้ UserInputService:IsKeyDown()

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

ชุดของ InputObjects ที่เกี่ยวข้องกับแป้นที่กดอยู่ในขณะนี้

ตัวอย่างโค้ด

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

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

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

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

Double Jump Key Combo

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local actionKey = Enum.KeyCode.LeftShift
local canJump = true
local canDoubleJump = false
local function jumpRequest()
local keysPressed = UserInputService:GetKeysPressed()
for _, key in ipairs(keysPressed) do
if key.KeyCode == actionKey and canJump then
canJump = false
canDoubleJump = true
end
end
end
local function stateChanged(oldState, newState)
-- Double jump during freefall if able to
if oldState == Enum.HumanoidStateType.Jumping and newState == Enum.HumanoidStateType.Freefall and canDoubleJump then
canDoubleJump = false
task.wait(0.2)
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
-- Allow player to jump again after they land
if oldState == Enum.HumanoidStateType.Freefall and newState == Enum.HumanoidStateType.Landed then
canJump = true
end
end
UserInputService.JumpRequest:Connect(jumpRequest)
humanoid.StateChanged:Connect(stateChanged)

GetLastInputType

ฟังก์ชันนี้ส่งคืน 'Enum.UserInputType' ที่เกี่ยวข้องกับการใส่ล่าสุดของผู้ใช้

ตัวอย่างเช่น หากการใส่ข้อมูลก่อนหน้าของผู้ใช้กดแป้นพิมพ์ว่างเปล่า ผลลัพธ์ Enum.UserInputType ที่ได้รับจะเป็น 'แป้นพิมพ์'

อีเวนต์ UserInputService.LastInputTypeChanged สามารถใช้เพื่อติดตามเมื่อมีการใช้ Enum.UserInputType ครั้งล่าสุดโดยผู้ใช้เปลี่ยนแปลง

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

The Enum.UserInputType ที่เกี่ยวข้องกับการป้อนล่าสุดของผู้ใช้

ตัวอย่างโค้ด

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

UserInputService:GetLastInputType

local UserInputService = game:GetService("UserInputService")
local lastInput = UserInputService:GetLastInputType()
if lastInput == Enum.UserInputType.Keyboard then
print("Most recent input was via keyboard")
end

GetMouseButtonsPressed

ฟังก์ชันนี้ส่งคืนคอลเลกชันของ InputObjects ที่ตรงกับปุ่มเมาส์ที่กําลังกดอยู่ในขณะนี้

ปุ่มเมาส์ที่ติดตามโดยฟังก์ชันนี้รวมถึง:


<td>คําอธิบาย</td>
</tr>
</thead>
<tr>
<td>ปุ่มเมาส์1</td>
<td>ปุ่มเมาส์ด้านซ้าย</td>
</tr>
<tr>
<td>ปุ่มเมาส์ 2</td>
<td>ปุ่มเมาส์ด้านขวา</td>
</tr>
<tr>
<td>ปุ่มเมาส์ 3</td>
<td>ปุ่มเมาส์ตรงกลาง</td>
</tr>
ชื่อ

หากผู้ใช้ไม่กดปุ่มเมาส์ลงเมื่อเรียกฟังก์ชันแล้ว จะส่งคืนรายการว่างเปล่า

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

ชุดของ InputObjects ที่ตรงกับปุ่มเมาส์ที่กําลังถูกกดอยู่ในขณะนี้

ตัวอย่างโค้ด

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

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

Check which MouseButtons are Pressed

local UserInputService = game:GetService("UserInputService")
-- InputBegan is a UserInputService event that fires when the player
-- begins interacting via a Human-User input device
UserInputService.InputBegan:Connect(function(_input, _gameProcessedEvent)
-- Returns an array of the pressed MouseButtons
local buttons = UserInputService:GetMouseButtonsPressed()
local m1Pressed, m2Pressed = false, false
for _, button in pairs(buttons) do
if button.UserInputType.Name == "MouseButton1" then
print("MouseButton1 is pressed")
m1Pressed = true
end
if button.UserInputType.Name == "MouseButton2" then
print("MouseButton2 is pressed")
m2Pressed = true
end
if m1Pressed and m2Pressed then
print("Both mouse buttons are pressed")
end
end
end)

GetMouseDelta

ฟังก์ชันนี้ส่งคืนการเปลี่ยนแปลงในพิกเซลของตำแหน่งของผู้เล่น Mouse ในเฟรมที่เรนเดอร์ล่าสุดเรนเดอร์เป็น Vector2ฟังก์ชันนี้ทำงานได้เฉพาะถ้าเมาส์ถูกล็อคโดยใช้คุณสมบัติ UserInputService.MouseBehaviorหากเมาส์ยังไม่ถูกล็อค ค่าที่ส่งคืน Vector2 จะเป็นศูนย์

ความไวของเมาส์ซึ่งกำหนดไว้ในการตั้งค่าของไคลเอนต์และ UserInputService.MouseDeltaSensitivity ผลการค้นหา

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

เปลี่ยนการเคลื่อนไหวของเมาส์

ตัวอย่างโค้ด

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

Getting Mouse Delta

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

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

GetMouseLocation

ฟังก์ชันนี้ส่งคืน Vector2 ที่แทนตำแหน่งหน้าจอปัจจุบันของผู้เล่น Mouse ในพิกเซลที่เกี่ยวข้องกับมุมซ้ายบนสิ่งนี้ไม่นับรวมกับ Enum.ScreenInsets เพื่อรับช่องว่างด้านบนซ้ายและด้านล่างขวา โทร GuiService:GetGuiInset()

หากตำแหน่งของเคอร์เซอร์อยู่นอกหน้าจอหรืออุปกรณ์ของผู้เล่นไม่มีเมาส์ ค่าที่ส่งกลับจะไม่สามารถกำหนดได้

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

A Vector2 ที่แทนตำแหน่งหน้าจอปัจจุบันของเมาส์ในพิกเซล

ตัวอย่างโค้ด

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

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

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

Move GUI To Mouse Location

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local gui = script.Parent
local screenGui = gui.Parent
screenGui.IgnoreGuiInset = true
local function moveGuiToMouse()
local mouseLocation = UserInputService:GetMouseLocation()
gui.Position = UDim2.fromOffset(mouseLocation.X, mouseLocation.Y)
end
moveGuiToMouse()
RunService:BindToRenderStep("moveGuiToMouse", 1, moveGuiToMouse)

GetNavigationGamepads

ฟังก์ชันนี้ส่งคืนคอลเลกชันของเกมแพด UserInputTypes ที่เชื่อมต่อและเปิดใช้งานสำหรับการนําทาง GUIรายการนี้อยู่ในลำดับลดลงของลําดับความสําคัญ ซึ่งหมายความว่าสามารถทําซ้ําได้เพื่อกําหนดว่าเกมแพดใดที่ควรมีการควบคุมการนําทาง

ว่าคอนโซลเกมที่เชื่อมต่อเป็นคอนโซลเกมการนําทางเท่านั้นจะกำหนดได้ว่าคอนโซลเกมใดควบคุม GUI การนําทางสิ่งนี้ไม่มีผลต่อการควบคุมการนำทาง

ตั้งแต่ UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

  • UserInputService:SetNavigationGamepad() , เพื่อเปิดใช้งานหรือปิดการใช้งานแป้นเกมสําหรับการนําทาง GUI
  • UserInputService:IsNavigationGamepad() เพื่อตรวจสอบว่าเกมแพดถูกเปิดใช้งานสำหรับการนําทาง GUI
  • UserInputService:GetConnectedGamepads() เพื่อคืนคอนโซลเกมทั้งหมดที่เชื่อมต่อไม่ว่าจะเป็นการควบคุมการนําทางของ GUI

ส่งค่ากลับ

ชุดของ UserInputTypes ที่สามารถใช้สําหรับการนําทาง GUI ในลําดับลําดับความสําคัญลง

GetStringForKeyCode

รับสตริงสําหรับรหัสกุญแจ ส่งคืนสตริงที่แทนที่กุญแจที่ผู้ใช้ควรกดเพื่อใส่ Enum.KeyCode ที่กำหนด โดยคํานึงถึงการจัดเค้าโครงแป้นพิมพ์ของพวกเขาสำหรับรหัสหลักที่ต้องการให้มีการถือบางตัวแก้ไขไว้ ฟังก์ชันนี้จะคืนรหัสหลักที่จะกดเพิ่มเติมจากตัวแก้ไขดูตัวอย่างด้านล่างสำหรับคำอธิบายเพิ่มเติม

เมื่อใช้ Roblox ด้วยเลย์เอาต์แป้นพิมพ์ที่ไม่ใช่ QWERTY รหัสกุญแจจะถูกแปลงเป็นตำแหน่ง QWERTY ที่เทียบเท่าตัวอย่างเช่น การกด A บนแป้นพิมพ์ AZERTY จะทำให้ได้ผลลัพธ์ Enum.KeyCode.Qการจัดเรียงนี้สามารถนำไปสู่ข้อมูลที่ไม่ตรงกันบนองค์ประกอบ UI ประสบการณ์ตัวอย่างเช่น "กด M เพื่อเปิดแผนที่" ไม่ถูกต้องบนแป้นพิมพ์ AZERTY; จะต้องเป็น "กด ? เพื่อเปิดแผนที่" ซึ่งอยู่ในตำแหน่งเดียวกับ M บน 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

<th>ค่ากลับ</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.Q</code></td>
<td><code>Q</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.W</code></td>
<td><code>W</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Equals</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>2</code> เพราะ <code>@</code> ถูกพิมพ์ด้วย <kbd>Shift</kbd><kbd>2</kbd></td>
</tr>
</tbody>
รหัสกุญแจ
ตัวอย่างบนแป้นพิมพ์ AZERTY

<th>ค่ากลับ</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.Q</code></td>
<td><code>A</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.W</code></td>
<td><code>Z</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Equals</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>É</code></td>
</tr>
</tbody>
รหัสกุญแจ
การใช้งานเกมแพด

ส่งคืนการแมพสตริงสำหรับเกมแพดที่เชื่อมต่อล่าสุดสำหรับเกมที่เชื่อมต่อล่าสุดหากคอนโทรลเลอร์ที่เชื่อมต่อไม่ได้รับการสนับสนุน ฟังก์ชันจะคืนค่าการแปลงสตริงเริ่มต้นสำหรับรหัสกุญแจที่ร้องขอ

ตัวอย่างต่อไปแสดงวิธีที่คุณสามารถแมพรายการสินทรัพย์ที่กําหนดเองสําหรับ 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 เพื่อให้แน่ใจว่าผู้ใช้เห็นปุ่มที่ถูกต้อง


<th>มูลค่าการคืนของ PlayStation</th>
<th>มูลค่าการคืน Xbox</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.ปุ่ม A</code></td>
<td><code>ปุ่มข้าม</code></td>
<td><code>ปุ่ม A</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ปุ่ม B</code></td>
<td><code>วงกลมปุ่ม</code></td>
<td><code>ปุ่ม B</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td><code>ปุ่มสแควร์</code></td>
<td><code>ปุ่ม X</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ปุ่มY</code></td>
<td><code>ปุ่มสามเหลี่ยม</code></td>
<td><code>ปุ่ม Y</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL1</code></td>
<td><code>ปุ่ม L1</code></td>
<td><code>ปุ่ม LB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL2</code></td>
<td><code>ปุ่ม L2</code></td>
<td><code>ปุ่มLT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL3</code></td>
<td><code>ปุ่ม L3</code></td>
<td><code>ปุ่มLS</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR1</code></td>
<td><code>ปุ่ม R1</code></td>
<td><code>ปุ่ม RB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR2</code></td>
<td><code>ปุ่ม R2</code></td>
<td><code>ปุ่ม RT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR3</code></td>
<td><code>ปุ่ม R3</code></td>
<td><code>ปุ่ม RS</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonStart</code></td>
<td><code>ตัวเลือกปุ่ม</code></td>
<td><code>ปุ่มเริ่มต้น</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonSelect</code></td>
<td><code>แป้ดสัมผัสปุ่ม</code> และ <code>แบ่งปันปุ่ม</code></td>
<td><code>ปุ่มเลือก</code></td>
</tr>
</tbody>
รหัสกุญแจ
ภาพระบบสําหรับ KeyCodes

เมื่อใช้ Enum.KeyCode ที่อาจแสดงได้ดีขึ้นในรูปแบบภาพ เช่น สำหรับ ImageLabel ในอินเทอร์เฟซผู้ใช้ คุณสามารถใช้ไอคอนมรดกต่อไปนี้ได้อย่างไรก็ตาม ขอแนะนำให้คุณใช้ GetImageForKeyCode() ในฐานะวิธีที่ทันสมัยและข้ามแพลตฟอร์มมากขึ้นในการดึงไอคอนควบคุม Xbox และ PlayStation


<th>ภาพ</th>
<th>รหัสสินทรัพย์</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxX.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxX.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonY</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxY.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxY.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonA</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxA.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxA.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonB</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxB.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadLeft</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadLeft.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/dpadLeft.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadRight</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadRight.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/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/การควบคุม/dpadUp.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadDown</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadDown.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/dpadDown.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonSelect</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxView.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxView.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonStart</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxmenu.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxmenu.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxLB.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxRB.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLT.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxLT.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRT.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxRT.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL3</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLS.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxLS.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR3</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRS.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/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/การควบคุม/xboxLSDirectional.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Thumbstick2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRSDirectional.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/xboxRSDirectional.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Backspace</code></td>
<td>
<img src="../../../assets/scripting/controls/backspace.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/backspace.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Return</code></td>
<td>
<img src="../../../assets/scripting/controls/return.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/return.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.LeftShift</code></td>
<td>
<img src="../../../assets/scripting/controls/shift.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/shift.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.RightShift</code></td>
<td>
<img src="../../../assets/scripting/controls/shift.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/shift.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Tab</code></td>
<td>
<img src="../../../assets/scripting/controls/tab.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/tab.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Quote</code></td>
<td>
<img src="../../../assets/scripting/controls/apostrophe.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/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/การควบคุม/comma.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Backquote</code></td>
<td>
<img src="../../../assets/scripting/controls/graveaccent.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/graveaccent.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Period</code></td>
<td>
<img src="../../../assets/scripting/controls/period.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/period.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Space</code></td>
<td>
<img src="../../../assets/scripting/controls/spacebar.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/การควบคุม/spacebar.png</code></td>
</tr>
</tbody>
รหัสกุญแจ

พารามิเตอร์

keyCode: Enum.KeyCode
ค่าเริ่มต้น: ""

ส่งค่ากลับ

GetSupportedGamepadKeyCodes

ฟังก์ชันนี้ส่งคืนคอลเลกชันของ KeyCodes ที่ gamepad ที่เกี่ยวข้องกับ Enum.UserInputType สนับสนุน

ฟังก์ชันนี้สามารถใช้เพื่อกำหนดว่า KeyCodes ใดที่สนับสนุนและไม่สนับสนุนโดย gamepad ที่เชื่อมต่อเพื่อตรวจสอบว่า KeyCode เฉพาะรองรับหรือไม่, ใช้ UserInputService:GamepadSupports() .

หากเรียกใช้ใน gamepad ที่ไม่มีอยู่หรือไม่ได้เชื่อมต่อ, ฟังก์ชันนี้จะส่งคืนคอลเลกชันว่างเปล่า

เนื่องจาก UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

gamepadNum: Enum.UserInputType

The Enum.UserInputType ของ gamepad

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ชุดของ KeyCodes ที่สนับสนุนโดย gamepad ที่กำหนดไว้

ตัวอย่างโค้ด

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

Binding Supported Gamepad KeyCodes

local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local function actionHandler(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
print("Action Handler: " .. actionName)
print(inputObject)
end
-- Since this function does not return anything, this handler will
-- "sink" the input and no other action handlers will be called after
-- this one.
end
local navGamepads = UserInputService:GetNavigationGamepads()
for _, gamepad in pairs(navGamepads) do
local supportedKeyCodes = UserInputService:GetSupportedGamepadKeyCodes(gamepad)
for _, keycode in pairs(supportedKeyCodes) do
if keycode == Enum.KeyCode.ButtonX then
ContextActionService:BindAction("SampleAction", actionHandler, false, Enum.KeyCode.ButtonX)
end
if keycode == Enum.KeyCode.X then
ContextActionService:BindAction("SampleAction", actionHandler, false, Enum.KeyCode.X)
end
end
end

IsGamepadButtonDown

ฟังก์ชันนี้ตรวจสอบว่าปุ่มบางปุ่มถูกกดบนเกมแพดบางตัวมันจะคืน true หาก gamepad มีการกด button ที่กำหนดไว้ด้านล่าง มิฉะนั้นจะคืนเป็นเท็จ

ประเภทการใส่ข้อมูลผู้ใช้ที่ถูกต้อง

คอนโซลเกมที่ระบุควรเป็นหนึ่งในมูลค่าเอนทิตีดังต่อไปนี้ของ UserInputType:


<tr>
<td>Enum.UserInputType.Gamepad1-8</td>
</tr>
ชื่อ
รหัสการกดที่ถูกต้อง

ปุ่มที่ระบุควรเป็นหนึ่งในตัวเลือกรหัสกุญแจต่อไปนี้:


<tr>
<td>Enum.KeyCode.ButtonX</td>
</tr>
<tr>
<td>Enum.KeyCode.ปุ่มY</td>
</tr>
<tr>
<td>Enum.KeyCode.ปุ่ม A</td>
</tr>
<tr>
<td>Enum.KeyCode.ปุ่ม B</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR1</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonL1</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR2</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonL2</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonR3</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonL3</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonStart</td>
</tr>
<tr>
<td>Enum.KeyCode.ButtonSelect</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadLeft</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadRight</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadUp</td>
</tr>
<tr>
<td>Enum.KeyCode.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

The Enum.UserInputType ของ gamepad ที่กำหนด

ค่าเริ่มต้น: ""
gamepadKeyCode: Enum.KeyCode

The Enum.KeyCode ของปุ่มที่ระบุ

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ว่าปุ่มเกมแพดที่ระบุบนเกมแพดที่กำหนดถูกกดหรือไม่

ตัวอย่างโค้ด

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

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

Special Action on Gamepad Button Combo

local UserInputService = game:GetService("UserInputService")
local activeGamepad = nil
local buttonX = Enum.KeyCode.ButtonX
local function isGamepadXDown()
if activeGamepad then
return UserInputService:IsGamepadButtonDown(activeGamepad, buttonX)
end
return false
end
local function input(_input, _gameProcessedEvent)
if not isGamepadXDown() then
-- Normal event
else
-- X Button down event
end
end
local function getActiveGamepad()
local activateGamepad = nil
local navigationGamepads = {}
navigationGamepads = UserInputService:GetNavigationGamepads()
if #navigationGamepads > 1 then
for i = 1, #navigationGamepads do
if activateGamepad == nil or navigationGamepads[i].Value < activateGamepad.Value then
activateGamepad = navigationGamepads[i]
end
end
else
local connectedGamepads = {}
connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for i = 1, #connectedGamepads do
if activateGamepad == nil or connectedGamepads[i].Value < activateGamepad.Value then
activateGamepad = connectedGamepads[i]
end
end
end
if activateGamepad == nil then -- nothing is connected, at least set up for gamepad1
activateGamepad = Enum.UserInputType.Gamepad1
end
end
return activateGamepad
end
if UserInputService.GamepadEnabled then
activeGamepad = getActiveGamepad()
UserInputService.InputBegan:Connect(input)
end

IsKeyDown

ฟังก์ชันนี้จะคืนว่าผู้ใช้กดค้างปุ่มที่เกี่ยวข้องกับกุญแจที่ให้ไว้ Enum.KeyCode หรือไม่มันจะคืน true หากกุญแจที่ระบุถูกกดหรือ false หากไม่ได้กด

สิ่งนี้สามารถใช้เพื่อตรวจสอบว่ากุญแจที่เฉพาะเจาะจง เช่น แถบพื้นที่ ถูกกดหรือไม่ ตัวอย่างเช่น:


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

เพื่อดึงรายการของทุกปุ่มที่กดโดยผู้ใช้ใช้ฟังก์ชัน UserInputService:GetKeysPressed()

ตั้งแต่ UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

  • Enum.UserInputType.IsGamepadButtonDown - อีเวนต์ที่คล้ายกันที่มีการใช้งานแตกต่างกัน: เพื่อตรวจสอบว่าให้กด button บน gamepad หรือไม่

พารามิเตอร์

keyCode: Enum.KeyCode

The Enum.KeyCode ของกุญแจ

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ว่ากุญแจที่ระบุถูกกดค้างไว้หรือไม่

ตัวอย่างโค้ด

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

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

Special Action on Key Combo Press

local UserInputService = game:GetService("UserInputService")
local shiftKeyL = Enum.KeyCode.LeftShift
local shiftKeyR = Enum.KeyCode.RightShift
-- Return whether left or right shift keys are down
local function isShiftKeyDown()
return UserInputService:IsKeyDown(shiftKeyL) or UserInputService:IsKeyDown(shiftKeyR)
end
-- Handle user input began differently depending on whether a shift key is pressed
local function input(_input, _gameProcessedEvent)
if not isShiftKeyDown() then
-- Normal input
else
-- Shift input
end
end
UserInputService.InputBegan:Connect(input)

IsMouseButtonPressed

ฟังก์ชันนี้ใช้ปุ่มเมาส์ Enum.UserInputType และส่งคืน bool ที่บ่งบอกว่ามันถูกกดอยู่ในปัจจุบัน

ปุ่มเมาส์ที่ตรวจสอบขึ้นอยู่กับค่า Enum.UserInputType ที่ส่งไปยังฟังก์ชันเป็นอาร์กิวเมนต์ ตัวอย่างเช่น:


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

ตั้งแต่ UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript"

พารามิเตอร์

mouseButton: Enum.UserInputType

The Enum.UserInputType ของปุ่มเมาส์

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ว่าปุ่มเมาส์ที่ให้ไว้ถูกกดค้างอยู่ในปัจจุบันหรือไม่

ตัวอย่างโค้ด

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

IsNavigationGamepad

ฟังก์ชันนี้ส่งคืน หากแป้ดเกมที่ระบุไว้สามารถควบคุมการนําทางและการเลือก ได้

หากต้องการตั้งค่าเกมแพดการนําทาง คุณสามารถใช้ UserInputService:SetNavigationGamepad() คุณยังสามารถใช้ UserInputService:GetNavigationGamepads() เพื่อรับรายการของเกมแพดการนําทางทั้งหมด

ตัวอย่างเช่น โค้ดด้านล่างตรวจสอบว่า gamepad1 เป็นเกมแผนที่หรือไม่:


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

The Enum.UserInputType ของ gamepad ที่ระบุ

ค่าเริ่มต้น: ""

ส่งค่ากลับ

ว่า gamepad ที่ระบุเป็น gamepad การนําทางหรือไม่

RecenterUserHeadCFrame

()

เฮดเซ็ทCFrame ของหูฟัง VR ไปยังการจัดตำแหน่งปัจจุบันของหูฟังที่สวมใส่โดยผู้ใช้ซึ่งหมายความว่าการจัดตำแหน่งปัจจุบันของหูฟังถูกตั้งค่าเป็น CFrame.new()

ใช้ฟังก์ชันนี้เพื่อย้ายไมโครโฟน CFrame ไปยังศูนย์กลางของพื้นที่เล่นถ้าดูเหมือนจะอยู่ในออฟเซ็ตแปลก

นี้ทำงานเหมือนกับฟังก์ชัน VRService และ VRService:RecenterUserHeadCFrame() อย่างเทียบเท่า

ตั้งแต่ UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript


ส่งค่ากลับ

()

ตัวอย่างโค้ด

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

UserInputService:RecenterUserHeadCFrame

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

SetNavigationGamepad

()

ฟังก์ชัน SetNavigationGamepad กำหนดว่า gamepad ที่ระบุ Enum.UserInputType สามารถย้ายตัวนําทาง GUI ได้หรือไม่แท่นควบคุมที่สามารถย้ายตัวนําทาง GUI ได้ถือเป็นแท่นควบคุมการนําทาง เกมแบบนำทาง

หากอาร์กิวเมนต์ เปิดใช้งาน ถูกส่งเป็น true แล้ว Gamepad สามารถย้ายตัวนําทาง GUI ได้หากอาร์กิวเมนต์เป็น false เกมแพดไม่สามารถย้ายตัวนําทาง GUI ได้

หากคุณต้องการตรวจสอบว่า Gamepad ที่กำหนดเป็น Gamepad สำหรับการนำทางเป็น Gamepad หรือไม่ คุณสามารถใช้ฟังก์ชัน UserInputService:IsNavigationGamepad()คุณยังสามารถใช้ UserInputService:GetNavigationGamepads() เพื่อดูรายการของแท่นเกมนำทางทั้งหมด

ตั้งแต่ UserInputService เป็นเฉพาะด้านไคลเอนต์เท่านั้น ฟังก์ชันนี้สามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

gamepadEnum: Enum.UserInputType

The Enum.UserInputType ของ gamepad ที่ระบุ

ค่าเริ่มต้น: ""
enabled: boolean

ว่าเกมแพดที่ระบุสามารถเคลื่อนย้ายนักนำทาง GUI ได้หรือไม่

ค่าเริ่มต้น: ""

ส่งค่ากลับ

()

ตัวอย่างโค้ด

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

UserInputService:SetNavigationGamepad

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

อีเวนต์

DeviceAccelerationChanged

อีเวนต์ DeviceAccelerationChanged จะเกิดขึ้นเมื่อผู้ใช้ย้ายอุปกรณ์ที่มีเครื่องวัดความเร่ง

เครื่องวัดความเร่งเป็นส่วนประกอบที่พบในอุปกรณ์เคลื่อนที่ส่วนใหญ่ที่วัดความเร่ง (การเปลี่ยนแปลงความเร็ว)

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีเครื่องวัดความเร่งเปิดใช้งานหรือไม่ ดู UserInputService.AccelerometerEnabled

อีเวนต์นี้สามารถใช้เพื่อติดตามการเคลื่อนไหวของอุปกรณ์ที่มีเครื่องวัดความเร่งการใช้งานตัวอย่างรวมถึงการย้ายตัวละครผู้เล่นเมื่ออุปกรณ์เคลื่อนที่เร่งความเร็ว

นอกจากนี้ อีเวนต์นี้สามารถใช้ร่วมกับ UserInputService:GetDeviceAcceleration() เพื่อกำหนดการเคลื่อนไหวปัจจุบันของอุปกรณ์ผู้ใช้หากอุปกรณ์มีเครื่องวัดความเร่ง

อีเวนต์นี้จะยิงท้องถิ่นเท่านั้น - ซึ่งหมายความว่าเฉพาะผู้เล่นที่อุปกรณ์เคลื่อนที่ได้เท่านั้นที่สามารถใช้อีเวนต์และจะทำงานได้เฉพาะใน LocalScript

พารามิเตอร์

acceleration: InputObject

An InputObject , ด้วย UserInputType ของ 'Accelerometer' และ Position ที่แสดงแรงโน้มถ่วงบนแต่ละแกนอุปกรณ์ท้องถิ่น


ตัวอย่างโค้ด

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

Control Players Using the Accelerometer

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local SENSITIVITY = 0.2
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local ready = true
local function changeAcceleration(acceleration)
if ready then
ready = false
local accel = acceleration.Position
if accel.Y >= SENSITIVITY then
humanoid.Jump = true
end
if accel.Z <= -SENSITIVITY then
humanoid:Move(Vector3.new(-1, 0, 0))
end
if accel.Z >= SENSITIVITY then
humanoid:Move(Vector3.new(1, 0, 0))
end
if accel.X <= -SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, 1))
end
if accel.X >= SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, -1))
end
task.wait(1)
ready = true
end
end
UserInputService.DeviceAccelerationChanged:Connect(changeAcceleration)

DeviceGravityChanged

อีเวนต์ จะเกิดขึ้นเมื่อแรงโน้มถ่วงของอุปกรณ์เปลี่ยนแปลงบนอุปกรณ์ที่มีเครื่องวัดความเร่ง

เวกเตอร์แรงโน้มถ่วงของอุปกรณ์แทนตัวแรงโน้มถ่วงบนแต่ละแกน X, Y และ Z ของอุปกรณ์แม้แรงโน้มถ่วงจะไม่เปลี่ยนแปลง แต่แรงที่มันใช้กับแต่ละแกนจะเปลี่ยนเมื่ออุปกรณ์หมุนและเปลี่ยนทิศทางมูลค่าแรงที่ใช้กับแต่ละแกนเป็นเวกเตอร์หน่วยที่มีช่วงตั้งแต่ -1 ถึง 1

เครื่องวัดความเร่งเป็นส่วนประกอบที่พบในอุปกรณ์เคลื่อนที่ส่วนใหญ่ที่วัดความเร่ง (การเปลี่ยนแปลงความเร็ว)

อีเวนต์นี้สามารถใช้เพื่อกำหนดทิศทางแรงโน้มถ่วงในโลกแบบจริงบนอุปกรณ์ของผู้ใช้นอกจากนี้ยังสามารถใช้เพื่อจำลองแรงโน้มถ่วงบนอุปกรณ์ของผู้ใช้ภายในเกม เช่น บนวัตถุในเกม (ดูตัวอย่างด้านล่าง)

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีเครื่องวัดความเร่งที่เปิดใช้งานหรือไม่ ดู UserInputService.AccelerometerEnabledหากอุปกรณ์มีเครื่องวัดความเร่งที่เปิดใช้งานคุณสามารถใช้ฟังก์ชัน UserInputService:GetDeviceGravity() เพื่อรับแรงโน้มถ่วงปัจจุบันบนอุปกรณ์ของผู้ใช้

พารามิเตอร์

gravity: InputObject

An InputObject , ด้วยคุณสมบัติ InputObject.Position ที่แสดงแรงโน้มถ่วงบนแต่ละแกนอุปกรณ์ท้องถิ่นตำแหน่งนี้สามารถใช้เป็นเส้นทางในการกำหนดทิศทางของแรงโน้มถ่วงเมื่อเทียบกับอุปกรณ์


ตัวอย่างโค้ด

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

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

Move a Ball using the Accelerometer

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

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

DeviceRotationChanged

อีเวนต์ DeviceRotationChanged จะเกิดขึ้นเมื่อผู้ใช้หมุนอุปกรณ์ที่มีเครื่องวัดความเร่ง

ไจโรสโคปเป็นส่วนประกอบที่พบในอุปกรณ์เคลื่อนที่ส่วนใหญ่ที่ตรวจจับการหมุนและความเร็วในการหมุน

อีเวนต์มีประโยชน์เมื่อติดตามการจัดตำแหน่งของอุปกรณ์และการเปลี่ยนแปลงตามที่ผู้ใช้หมุนอุปกรณ์ของตนเพื่อกำหนดการหมุนอุปกรณ์ปัจจุบันคุณสามารถใช้ฟังก์ชัน UserInputService:GetDeviceRotation()

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีการเปิดใช้งานเครื่องวัดความเร่งหรือไม่ และเหตุการณ์นี้จะเกิดขึ้น ดู UserInputService.GyroscopeEnabled

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

พารามิเตอร์

rotation: InputObject

An InputObject ให้ข้อมูลเกี่ยวกับการหมุนของอุปกรณ์InputObject.Position แทนที่การหมุนใหม่มูลค่าตำแหน่ง Vector3 และ InputObject.Delta แทนการเปลี่ยนแปลงในการหมุนในมูลค่าตำแหน่ง Vector3

cframe: CFrame

A CFrame ที่แทนตำแหน่งปัจจุบันของอุปกรณ์


ตัวอย่างโค้ด

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

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

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

Move a Ball using the Accelerometer

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

GamepadConnected

อีเวนต์ GamepadConnected จะเกิดขึ้นเมื่อมีการเชื่อมต่อเกมแพดกับไคลเอนต์

เนื่องจากเกม Roblox สนับสนุนตัวควบคุมหลายตัว อีเวนต์นี้มีประโยชน์เมื่อจับคู่กับอีเวนต์ UserInputService.GamepadDisconnected เพื่อติดตามตัวควบคุม/เกมแพดที่ใช้งานอยู่คุณยังสามารถใช้ UserInputService:GetConnectedGamepads() เพื่อค้นหา gamepad ที่ถูกต้องเพื่อใช้

ตัวอย่างต่อไปนี้แสดงตัวอย่างการใช้งานของการติดตามเมื่อเกมแพดเชื่อมต่อกับไคลเอนต์


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

หากต้องการดูอุปกรณ์ที่เชื่อมต่อ คุณสามารถใช้ฟังก์ชัน UserInputService:GetConnectedGamepads()

เนื่องจากอีเวนต์นี้จะเกิดขึ้นในท้องถิ่นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

gamepadNum: Enum.UserInputType

The Enum.UserInputType ของ gamepad ที่เชื่อมต่อ


GamepadDisconnected

อีเวนต์ GamepadDisconnected จะเกิดขึ้นเมื่อมีการตัดการเชื่อมต่อเกมแพด

เนื่องจากเกม Roblox สนับสนุนตัวควบคุมหลายตัว อีเวนต์นี้มีประโยชน์เมื่อจับคู่กับอีเวนต์ UserInputService.GamepadConnected เพื่อติดตามตัวควบคุม/เกมแพดที่ใช้งานอยู่คุณยังสามารถใช้ UserInputService:GetConnectedGamepads() เพื่อค้นหา gamepad ที่ถูกต้องเพื่อใช้

ตัวอย่างต่อไปนี้แสดงตัวอย่างการใช้งานเมื่อแท็บเล็ตถูกถอดจากไคลเอนต์


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

เนื่องจากอีเวนต์นี้จะเกิดขึ้นในท้องถิ่นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

gamepadNum: Enum.UserInputType

The Enum.UserInputType ของ gamepad ที่ถูกตัดการเชื่อมต่อ


InputBegan

อีเวนต์ InputBegan จะเกิดขึ้นเมื่อผู้ใช้เริ่มโต้ตอบผ่านอุปกรณ์อินเทอร์เฟซมนุษย์-คอมพิวเตอร์ (ปุ่มเมาส์ลง, แตะเริ่ม, ปุ่มพิมพ์ลง, เป็นต้น)

สามารถใช้เพื่อติดตามจุดเริ่มต้นของการโต้ตอบของผู้ใช้ เช่น เมื่อผู้ใช้เริ่มโต้ตอบกับองค์ประกอบ GUI คอนโซลเกม ฯลฯมันไม่ได้จับการเคลื่อนไหวของล้อเมาส์

อีเวนต์นี้สามารถใช้ร่วมกับ UserInputService.InputChanged และ UserInputService.InputEnded เพื่อติดตามเมื่อการป้อนข้อมูลของผู้ใช้เริ่มต้นการเปลี่ยนแปลง และสิ้นสุด

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

พารามิเตอร์

ตัวอย่าง InputObject ซึ่งมีข้อมูลเกี่ยวกับการใส่ของผู้ใช้

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

Handling InputBegan

-- In order to use the InputBegan event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- A sample function providing multiple usage cases for various types of user input
UserInputService.InputBegan:Connect(function(input, gameProcessed)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key is being pushed down! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has started at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button is being pressed on a gamepad! Button:", input.KeyCode)
end
if gameProcessed then
print("The game engine internally observed this input!")
else
print("The game engine did not internally observe this input!")
end
end)

InputChanged

อีเวนต์ InputChanged จะเกิดขึ้นเมื่อผู้ใช้เปลี่ยนวิธีการโต้ตอบผ่านอุปกรณ์อินเทอร์เฟซมนุษย์-คอมพิวเตอร์ (ปุ่มเมาส์ลง, แตะเริ่ม, ปุ่มพิมพ์ลง, เป็นต้น)

เพื่อเพิกเฉยกิจกรรมที่จัดการโดยอัตโนมัติโดย Roblox เช่นการเลื่อนใน ScrollingFrame ตรวจสอบว่าอาร์กิวเมนต์ gameProcessedEvent เป็นเท็จอีเวนต์นี้สามารถใช้ร่วมกับ UserInputService.InputBegan และ UserInputService.InputEnded เพื่อติดตามเมื่อการใส่ข้อมูลของผู้ใช้เริ่มต้นการเปลี่ยนแปลง และสิ้นสุด

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

พารามิเตอร์

ตัวอย่าง InputObject ซึ่งมีข้อมูลเกี่ยวกับการใส่ของผู้ใช้

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

Handling InputChanged

-- In order to use the InputChanged event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- Prints the current input position and the change (delta) in position
local function printMovement(input)
print("Position:", input.Position)
print("Movement Delta:", input.Delta)
end
-- A sample function providing multiple usage cases for various types of user input
local function InputChanged(input, _gameProcessed)
if input.UserInputType == Enum.UserInputType.MouseMovement then
print("The mouse has been moved!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
print("The mouse wheel has been scrolled!")
print("Wheel Movement:", input.Position.Z)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
if input.KeyCode == Enum.KeyCode.Thumbstick1 then
print("The left thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.Thumbstick2 then
print("The right thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.ButtonL2 then
print("The pressure being applied to the left trigger has changed!")
print("Pressure:", input.Position.Z)
elseif input.KeyCode == Enum.KeyCode.ButtonR2 then
print("The pressure being applied to the right trigger has changed!")
print("Pressure:", input.Position.Z)
end
elseif input.UserInputType == Enum.UserInputType.Touch then
print("The user's finger is moving on the screen!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.Gyro then
local _rotInput, rotCFrame = UserInputService:GetDeviceRotation()
local rotX, rotY, rotZ = rotCFrame:toEulerAnglesXYZ()
local rot = Vector3.new(math.deg(rotX), math.deg(rotY), math.deg(rotZ))
print("The rotation of the user's mobile device has been changed!")
print("Position", rotCFrame.p)
print("Rotation:", rot)
elseif input.UserInputType == Enum.UserInputType.Accelerometer then
print("The acceleration of the user's mobile device has been changed!")
printMovement(input)
end
end
UserInputService.InputChanged:Connect(InputChanged)

InputEnded

อีเวนต์ InputEnded จะเกิดขึ้นเมื่อผู้ใช้หยุดโต้ตอบผ่านอุปกรณ์อินเทอร์เฟซมนุษย์-คอมพิวเตอร์ (ปุ่มเมาส์ลง, แตะเริ่ม, ปุ่มพิมพ์ลง, เป็นต้น)มันมีประโยชน์เมื่อติดตามเมื่อผู้ใช้ปล่อยแป้นพิมพ์ ปุ่มเมาส์ การแตะหน้าจอ ฯลฯ

อีเวนต์นี้สามารถใช้ร่วมกับ UserInputService.InputBegan และ UserInputService.InputChanged เพื่อติดตามเมื่อการป้อนข้อมูลของผู้ใช้เริ่มต้นการเปลี่ยนแปลง และสิ้นสุด

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

พารามิเตอร์

ตัวอย่าง InputObject ซึ่งมีข้อมูลเกี่ยวกับการใส่ข้อมูลของผู้ใช้

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

Handling InputEnded

-- In order to use the InputChanged event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- A sample function providing multiple usage cases for various types of user input
UserInputService.InputEnded:Connect(function(input, gameProcessed)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key has been released! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button has been released on a gamepad! Button:", input.KeyCode)
end
if gameProcessed then
print("The game engine internally observed this input!")
else
print("The game engine did not internally observe this input!")
end
end)

JumpRequest

อีเวนต์ JumpRequest UserInputService จะเกิดขึ้นเมื่อมีคำขอกระโดดจากไคลเอนต์ เช่น เมื่อไคลเอนต์กดปุ่มช่องว่างหรือปุ่มกระโดดบนมือถือ

อีเวนต์นี้จะเกิดขึ้นเมื่อใดก็ตามที่ผู้ใช้พยายามทำการกระโดด Player.Characterพฤติกรรมเริ่มต้นตอบสนองคำขอกระโดดโดยการตั้งค่าคุณสมบัติ Humanoid.Jump ของผู้เล่นเป็นจริงซึ่งทำให้ตัวละครของผู้เล่นกระโดด

อีเวนต์สามารถใช้เพื่อติดตามทุกครั้งที่ผู้เล่นต้องการกระโดดแทนที่จะใช้เพื่อทำให้ผู้เล่นกระโดด ควรใช้เพื่อเปลี่ยนพฤติกรรมการกระโดดเริ่มต้น - เช่น ปิดการกระโดด

ตัวอย่างเช่น โค้ดด้านล่างจะพิมพ์ "กระโดด" ทุกครั้งที่ผู้เล่นส่งคำขอกระโดด


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

เนื่องจากอีเวนต์นี้จะเกิดขึ้นหลายครั้งสําหรับคําขอกระโดดเดียวโดยใช้ debounce จึงแนะนําให้ใช้

หากคุณต้องการเชื่อมต่อแป้นหรือปุ่มไปยังการดำเนินการอื่น ๆ ให้พิจารณาใช้เหตุการณ์เช่น UserInputService:GetKeysPressed() และ UserInputService.InputBegan หรือ ContextActionService

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript


ตัวอย่างโค้ด

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

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

Disable Jumping

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
-- Fires when the user tries to jump
local function jump()
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
end
UserInputService.JumpRequest:Connect(jump)

LastInputTypeChanged

อีเวนต์ UserInputService.LastInputTypeChanged จะเกิดขึ้นเมื่อใดก็ตามที่ไคลเอนต์เปลี่ยนวิธีการโต้ตอบผ่านอุปกรณ์อินเทอร์เฟซมนุษย์-คอมพิวเตอร์(i.e.จาก MouseMovement ไปยัง MouseWheel หรือจาก Thumbstick1 ไปยัง Thumbstick2)

พิมพ์ไม่ว่าจะเปลี่ยนแปลงหรือไม่ คุณสามารถใช้ฟังก์ชัน UserInputService:GetLastInputType()

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

พารามิเตอร์

lastInputType: Enum.UserInputType

A Enum.UserInputType พิมพ์


ตัวอย่างโค้ด

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

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

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

Hide Mouse During Keyboard Input

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

PointerAction

PointerAction แอ็คชันเช่น การเลื่อนล้อเมาส์

พารามิเตอร์

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

TextBoxFocusReleased

อีเวนต์ TextBoxFocusReleased จะเกิดขึ้นเมื่อไคลเอนต์สูญเสียการโฟกัสบน TextBox โดยปกติเมื่อไคลเอนต์หยุดการป้อนข้อความโดยการกดกลับหรือคลิก/แตะที่อื่นบนหน้าจอ

ตัวอย่างเช่น โค้ดด้านล่างจะพิมพ์ชื่อของ TextBox ที่สูญเสียการโฟกัสเมื่อเหตุการณ์เกิดขึ้น


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

สามารถใช้ร่วมกับ UserInputService.TextBoxFocused เพื่อติดตามเมื่อมีการได้รับและสูญเสียความโฟกัสของ TextBox

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่มเติม

พารามิเตอร์

textboxReleased: TextBox

The TextBox ที่สูญเสียการโฟกัส


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

The TextBox ที่ได้รับความสนใจ


TouchDrag

พารามิเตอร์

dragDirection: Enum.SwipeDirection
numberOfTouches: number
gameProcessedEvent: boolean

TouchEnded

อีเวนต์ TouchEnded จะเกิดขึ้นเมื่อผู้ใช้ปล่อยนิ้วออกจากหน้าจอของอุปกรณ์ที่เปิดใช้งานการสัมผัส สิ้นสุดการป้อนข้อมูลด้วยอุปกรณ์

อีเวนต์นี้สามารถใช้เพื่อกำหนดเวลาที่ผู้ใช้หยุดสัมผัสหน้าจอของอุปกรณ์ของตนสามารถจับคู่กับ UserInputService.TouchStarted เพื่อกำหนดเวลาที่ผู้ใช้เริ่มและหยุดสัมผัสหน้าจอ

ตัวอย่างเช่น รหัสด้านล่างจะพิมพ์ตำแหน่งหน้าจอที่ผู้ใช้หยุดสัมผัสหน้าจอ


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

วัตถุการสัมผัสเป็นวัตถุการสัมผัสเดียวกันตลอดอายุของการสัมผัสดังนั้นการเปรียบเทียบ InputObjects เมื่อพวกเขาเป็นวัตถุสัมผัสจะถูกต้องเพื่อกำหนดว่ามันเป็นนิ้วเดียวกันหรือไม่

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีการเปิดใช้งานการสัมผัสหรือไม่ และการสัมผัสจะยิงไฟขึ้น ดู UserInputService.TouchEnabled

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

ตัวอย่าง InputObject ซึ่งมีข้อมูลเกี่ยวกับการใส่ของผู้ใช้

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

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

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

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchLongPress

ยิงเมื่อผู้ใช้กดนิ้วอย่างน้อยหนึ่งนิ้วเป็นเวลาสั้นๆ ในตำแหน่งหน้าจอเดียวกันของอุปกรณ์ที่เปิดใช้งานแตะ

อีเวนต์นี้สามารถใช้เพื่อกำหนดเวลาที่ผู้ใช้กดนิ้วลงบนสิ่งในเกม GuiObject หรือองค์ประกอบ

ตัวอย่างด้านล่างพิมพ์ state ของการกดยาวเมื่อผู้ใช้กดนิ้วอย่างน้อยหนึ่งนิ้วเป็นเวลาสั้นๆ ในตำแหน่งหน้าจอเดียวกันสถานะที่เป็นไปได้รวมถึง: เริ่ม , เปลี่ยน , สิ้นสุด , ยกเลิก และ ไม่มี


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.TouchStarted และ UserInputService.TouchEnded เพื่อกำหนดเวลาที่ผู้ใช้เริ่มและหยุดสัมผัสหน้าจอ

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

touchPositions: Array

ชุดของวัตถุ Vector2 ที่ระบุตำแหน่งของนิ้วที่มีส่วนร่วมในท่าทาง

The Enum.UserInputState ของท่าทาง

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

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

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

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchMoved

จะเกิดไฟไหม้เมื่อผู้ใช้ย้ายนิ้วบนอุปกรณ์ TouchEnabled เช่นแท็บเล็ตหรือสมาร์ทโฟน

อีเวนต์นี้มีประโยชน์สำหรับการติดตามว่าผู้ใช้กำลังย้ายนิ้วบนหน้าจอหรือไม่เช่นเดียวกับสถานที่ที่ผู้ใช้กำลังย้ายนิ้ว

รหัสด้านล่างแสดงการสัมผัสที่เคลื่อนจากตำแหน่งก่อนหน้าไปยังตำแหน่งใหม่บนอุปกรณ์ TouchEnabledโปรดทราบว่า InputObject.Position บนพารามิเตอร์ touch ที่ส่งมาเป็น Vector3 แต่รวมถึง X และ Y เท่านั้น; Z เป็น 0 เสมอ


local UserInputService = game:GetService("UserInputService")
function onTouchMoved(touch, gameProcessedEvent)
local oldPosition = touch.Position - touch.Delta
print("Touch moved from " .. tostring(oldPosition) .. " to " .. tostring(touch.Position))
end
UserInputService.TouchMoved:Connect(onTouchMoved)

จับคู่เหตุการณ์นี้กับ UserInputService.TouchStarted และ UserInputService.TouchEnded เพื่อกำหนดเวลาที่ผู้ใช้เริ่มสัมผัสหน้าจอ วิธีที่นิ้วของพวกเขาเคลื่อนที่ในขณะสัมผัส และเมื่อพวกเขาหยุดสัมผัสหน้าจอ

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้สนับสนุนการแตะและการแตะจะเกิดขึ้นหรือไม่ ดู UserInputService.TouchEnabled

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

ตัวอย่าง InputObject ซึ่งมีข้อมูลเกี่ยวกับการใส่ของผู้ใช้

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

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

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

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchPan

อีเวนต์ 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

ความเร็วของการเคลื่อนไหวของกระทะ (ในพิกเซล) ต่อวินาที

The Enum.UserInputState ของท่าทาง

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

TouchPinch

ยิงเมื่อผู้ใช้วางและย้ายนิ้วสองนิ้วบนหน้าจอของอุปกรณ์ 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

ความเร็วของการกดปุ่ม (ในพิกเซล) ต่อวินาที

The Enum.UserInputState ของท่าทาง

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

TouchRotate

อีเวนต์ 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

ชุดของ Vector2s ซึ่งบ่งบอกถึงตำแหน่งของนิ้วที่มีส่วนร่วมในท่าทาง

rotation: number

จํานวนองศาที่การกดที่เคลื่อนไปตั้งแต่เริ่มต้นของการกด

velocity: number

การเปลี่ยนแปลงในการหมุน (ในองศา) หารด้วยระยะเวลาการเปลี่ยนแปลง (ในวินาที)

The Enum.UserInputState ของท่าทาง

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

TouchStarted

อีเวนต์ TouchStarted จะเกิดขึ้นเมื่อผู้ใช้วางนิ้วบนอุปกรณ์ TouchEnabled เริ่มการป้อนข้อมูลด้วยอุปกรณ์

อีเวนต์นี้สามารถใช้เพื่อกำหนดเวลาที่ผู้ใช้เริ่มสัมผัสหน้าจอของอุปกรณ์ได้สามารถจับคู่กับ UserInputService.TouchEnded เพื่อกำหนดเวลาที่ผู้ใช้เริ่มและหยุดสัมผัสหน้าจอ

วัตถุการสัมผัสเป็นวัตถุการสัมผัสเดียวกันตลอดอายุของการสัมผัสดังนั้นการเปรียบเทียบ InputObjects เมื่อพวกเขาเป็นวัตถุสัมผัสจะถูกต้องเพื่อกำหนดว่ามันเป็นนิ้วเดียวกันหรือไม่

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีการเปิดใช้งานการสัมผัสหรือไม่ และการสัมผัสจะยิงไฟขึ้น ดู UserInputService.TouchEnabled

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

ตัวอย่าง InputObject ซึ่งมีข้อมูลเกี่ยวกับการใส่ของผู้ใช้

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

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

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

Tracking Touches

local UserInputService = game:GetService("UserInputService")
local dragging
local dragInput
local dragStart
local startPos
local gui = script.Parent
local function touchStarted(input, _gameProcessed)
if not dragging then
dragging = true
dragInput = input
dragStart = input.Position
startPos = gui.Position
end
end
local function update(input, _gameProcessed)
if input == dragInput and dragging then
local delta = input.Position - dragStart
gui.Position =
UDim2.new(startPos.X.Scale, startPos.X.Offset + delta.X, startPos.Y.Scale, startPos.Y.Offset + delta.Y)
end
end
local function touchEnded(input, _gameProcessed)
if input == dragInput then
dragging = false
end
end
UserInputService.TouchStarted:Connect(touchStarted)
UserInputService.TouchMoved:Connect(update)
UserInputService.TouchEnded:Connect(touchEnded)

TouchSwipe

อีเวนต์ TouchSwipe จะเกิดขึ้นเมื่อผู้ใช้สไลด์นิ้วบนอุปกรณ์ TouchEnabled

อีเวนต์นี้สามารถใช้เพื่อกำหนดเวลาที่ผู้ใช้เลื่อนนิ้วบนหน้าจออุปกรณ์ของตนและทิศทางที่ผู้ใช้เลื่อน

สำหรับการติดตามการเคลื่อนไหวของการสัมผัสที่แม่นยำมากขึ้นใช้ UserInputService.TouchMoved

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีการเปิดใช้งานการสัมผัสหรือไม่ และการสัมผัสจะยิงไฟขึ้น ดู UserInputService.TouchEnabled

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

swipeDirection: Enum.SwipeDirection

An Enum.SwipeDirection , ระบุทิศทางที่ผู้ใช้สไลด์

numberOfTouches: number

จํานวนการสัมผัส (เช่นนิ้ว) ที่มีส่วนร่วมในท่าทาง

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

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

Touch Swipe a GUI

local UserInputService = game:GetService("UserInputService")
local gui = script.Parent
local swipePositionY = gui.Position.Y.Offset
local swipePositionX = gui.Position.X.Offset
local camera = workspace.CurrentCamera
local maxY = camera.ViewportSize.Y - gui.Size.Y.Offset
local maxX = camera.ViewportSize.X - gui.Size.X.Offset
local function TouchSwipe(swipeDirection, _numberOfTouches, _gameProcessedEvent)
if swipeDirection == Enum.SwipeDirection.Up then
swipePositionY = math.max(swipePositionY - 200, 0)
elseif swipeDirection == Enum.SwipeDirection.Down then
swipePositionY = math.min(swipePositionY + 200, maxY)
elseif swipeDirection == Enum.SwipeDirection.Left then
swipePositionX = math.max(swipePositionX - 200, 0)
elseif swipeDirection == Enum.SwipeDirection.Right then
swipePositionX = math.min(swipePositionX + 200, maxX)
end
gui:TweenPosition(UDim2.new(0, swipePositionX, 0, swipePositionY), "Out", "Quad", 0.25, true)
end
UserInputService.TouchSwipe:Connect(TouchSwipe)

TouchTap

อีเวนต์ TouchTap จะเกิดขึ้นเมื่อผู้ใช้แตะ/แตะนิ้วบนหน้าจอบนอุปกรณ์ TouchEnabled

อีเวนต์นี้จะยิงไม่ว่าผู้ใช้จะสัมผัส/แตะโลกเกมหรือองค์ประกอบ GuiObjectหากคุณกำลังมองหาอีเวนต์ที่จะเปิดใช้งานเฉพาะเมื่อผู้ใช้แตะ/แตะโลกเกม ให้ใช้ UserInputService.TouchTapInWorld

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีการเปิดใช้งานการสัมผัสหรือไม่ และการสัมผัสจะยิงไฟขึ้น ดู UserInputService.TouchEnabled

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript

พารามิเตอร์

touchPositions: Array

ชุดของวัตถุ Vector2 ที่ระบุตำแหน่งของนิ้วที่มีส่วนร่วมในการแตะ

gameProcessedEvent: boolean

บ่งบอกว่าเครื่องเกมภายในสังเกตการเข้ารหัสนี้และดำเนินการกับมันหรือไม่โดยทั่วไปนี้หมายถึงการประมวลผล UI ดังนั้นหากปุ่มถูกแตะหรือคลิกจากอินพุตนี้ gameProcessedEvent จะเป็น trueสิ่งนี้เป็นจริงสำหรับอีเวนต์การป้อนที่เชื่อมต่อผ่าน ContextActionService เช่นกัน


ตัวอย่างโค้ด

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

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

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

The Difference Between TouchTap and TouchLongPress

local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end

TouchTapInWorld

อีเวนต์ TouchTapInWorld จะเกิดขึ้นเมื่อผู้ใช้แตะ/แตะนิ้วบนหน้าจอบนอุปกรณ์ TouchEnabledมันถูกยิงเมื่อผู้ใช้แตะในโลกเกม

อีเวนต์นี้สามารถใช้เพื่อกำหนดเวลาที่ผู้ใช้แตะหน้าจอและไม่แตะองค์ประกอบ GuiObjectหากผู้ใช้แตะองค์ประกอบ GUI UserInputService.TouchTap จะยิงแทน TouchTapInWorld

เพื่อตรวจสอบว่าอุปกรณ์ของผู้ใช้มีการเปิดใช้งานการสัมผัสหรือไม่ และการสัมผัสจะยิงไฟขึ้น ดู UserInputService.TouchEnabled

อีเวนต์นี้จะยิงเฉพาะเมื่อหน้าต่างไคลเอนต์ Roblox อยู่ในโฟกัส ตัวอย่างเช่น การใส่ข้อมูลจะไม่ถูกจับเมื่อหน้าต่างถูกลดขนาดลง

เนื่องจากมันจะยิงท้องถิ่นเท่านั้น จึงสามารถใช้ได้เฉพาะใน LocalScript

ดูเพิ่ม:

พารามิเตอร์

position: Vector2

A Vector2 บ่งบอกตำแหน่งของการสัมผัส

processedByUI: boolean

ว่าผู้ใช้แตะองค์ประกอบ GUI หรือไม่


ตัวอย่างโค้ด

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

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

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

Create a Part in World at Touch Position

local UserInputService = game:GetService("UserInputService")
local camera = workspace.CurrentCamera
local LENGTH = 500
local function createPart(position, processedByUI)
-- Do not create a part if the player clicked on a GUI/UI element
if processedByUI then
return
end
-- Get Vector3 world position from the Vector2 viewport position
local unitRay = camera:ViewportPointToRay(position.X, position.Y)
local ray = Ray.new(unitRay.Origin, unitRay.Direction * LENGTH)
local hitPart, worldPosition = workspace:FindPartOnRay(ray)
-- Create a new part at the world position if the player clicked on a part
-- Do not create a new part if player clicks on empty skybox
if hitPart then
local part = Instance.new("Part")
part.Parent = workspace
part.Anchored = true
part.Size = Vector3.new(1, 1, 1)
part.Position = worldPosition
end
end
UserInputService.TouchTapInWorld:Connect(createPart)

WindowFocusReleased

อีเวนต์ WindowFocusReleased จะเกิดขึ้นเมื่อหน้าต่างของไคลเอนต์ Roblox สูญเสียโฟกัส - โดยปกติเมื่อไคลเอนต์ Roblox ถูกลดขนาดโดยผู้ใช้

ตัวอย่างเช่น รหัสด้านล่างจะพิมพ์ "การโฟกัสหน้าต่างเผยแพร่แล้ว" เมื่อไหร่ที่ไคลเอนต์ Roblox สูญเสียการโฟกัส


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

อีเวนต์นี้สามารถใช้ร่วมกับ UserInputService.WindowFocused เพื่อติดตามว่าไคลเอนต์ Roblox มุ่งเน้นไปที่หน้าจอของผู้ใช้อยู่หรือไม่

เนื่องจากมันจะยิงท้องถิ่นเท่านั้น จึงสามารถใช้ได้เฉพาะใน LocalScript


ตัวอย่างโค้ด

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

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

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

Window Focus AFK Script (Script)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = Instance.new("RemoteEvent")
afkEvent.Name = "AfkEvent"
afkEvent.Parent = ReplicatedStorage
local function setAfk(player, afk)
if afk then
local forcefield = Instance.new("ForceField")
forcefield.Parent = player.Character
else
local forcefield = player.Character:FindFirstChildOfClass("ForceField")
if forcefield then
forcefield:Destroy()
end
end
end
afkEvent.OnServerEvent:Connect(setAfk)

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

Window Focus AFK Script (LocalScript)

local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = ReplicatedStorage:WaitForChild("AfkEvent")
local function focusGained()
afkEvent:FireServer(false)
end
local function focusReleased()
afkEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)

WindowFocused

อีเวนต์โฟกัสหน้าต่างจะเกิดขึ้นเมื่อหน้าต่างของไคลเอนต์ Roblox ได้รับการโฟกัส - โดยปกติเมื่อไคลเอนต์ Roblox ถูกเพิ่มสูงสุด/เปิดอยู่บนหน้าจอของผู้ใช้

ตัวอย่างเช่น รหัสด้านล่างจะพิมพ์ "การโฟกัสหน้าต่าง" เมื่อไหร่ที่ไคลเอนต์ Roblox ได้รับการโฟกัส


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

อีเวนต์นี้สามารถใช้ร่วมกับ UserInputService.WindowFocusReleased เพื่อติดตามว่าไคลเอนต์ Roblox มุ่งเน้นไปที่หน้าจอของผู้ใช้อยู่หรือไม่

เนื่องจากอีเวนต์นี้จะเกิดขึ้นเฉพาะในท้องถิ่นเท่านั้นจึงสามารถใช้ได้เฉพาะใน LocalScript


ตัวอย่างโค้ด

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

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

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

Window Focus AFK Script (Script)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = Instance.new("RemoteEvent")
afkEvent.Name = "AfkEvent"
afkEvent.Parent = ReplicatedStorage
local function setAfk(player, afk)
if afk then
local forcefield = Instance.new("ForceField")
forcefield.Parent = player.Character
else
local forcefield = player.Character:FindFirstChildOfClass("ForceField")
if forcefield then
forcefield:Destroy()
end
end
end
afkEvent.OnServerEvent:Connect(setAfk)

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

Window Focus AFK Script (LocalScript)

local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = ReplicatedStorage:WaitForChild("AfkEvent")
local function focusGained()
afkEvent:FireServer(false)
end
local function focusReleased()
afkEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)