UserInputService
*Nội dung này được dịch bằng AI (Beta) và có thể có lỗi. Để xem trang này bằng tiếng Anh, hãy nhấp vào đây.
UserInputService là một dịch vụ được sử dụng để phát hiện và thu nhận các loại đầu vào khác nhau có sẵn trên thiết bị của người dùng.
Mục đích chính của dịch vụ này là cho phép các trải nghiệm hợp tác với nhiều hình thức nhập có sẵn, như gamepad, màn hình cảm ứng và bàn phím.Nó cho phép một LocalScript thực hiện các hành động khác nhau tùy thuộc vào thiết bị và, cuối cùng, cung cấp trải nghiệm tốt nhất cho người dùng cuối cùng.
Một số cách sử dụng của dịch vụ này bao gồm việc phát hiện nhập của người dùng khi họ tương tác với GUI, công cụ và các trường hợp trò chơi khác.Để phát hiện nhập력 của người dùng, dịch vụ phải tìm kiếm sự kiện dịch vụ.Ví dụ, dịch vụ có thể phát hiện sự kiện như khi người dùng chạm vào màn hình của thiết bị di động bằng cách sử dụng UserInputService.TouchStarted , hoặc kết nối gamepad như một điều khiển Xbox vào thiết bị của họ bằng cách sử dụng UserInputService.GamepadConnected .
Vì dịch vụ này chỉ dành cho phía khách hàng, nó chỉ hoạt động khi được sử dụng trong một LocalScript hoặc một ModuleScript được yêu cầu bởi một LocalScript .Vì UserInputService chỉ là bên khách, người dùng trong trò chơi chỉ có thể phát hiện ra đầu vào của riêng họ - và không phải đầu vào của người khác.
Xem thêm ContextActionService , một dịch vụ cho phép bạn gắn chức năng vào nhiều đầu vào người dùng.
Mẫu mã
The following example demonstrates one of many usage examples of handling a UserInputService event.
-- 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)
Tóm Tắt
Thuộc Tính
Mô tả xem thiết bị của người dùng có có accelerometer hay không.
Mô tả xem thiết bị đang được sử dụng bởi người dùng có gamepad có sẵn hay không.
Mô tả xem thiết bị của người dùng có gyroscope hay không.
Mô tả xem thiết bị của người dùng có bàn phím sẵn không.
Xác định xem chuột của người dùng có thể di chuyển tự do hay bị khóa.
Tăng mức độ delta (thay đổi) của đầu ra của người dùng Mouse .
Mô tả xem thiết bị của người dùng có có sẵn chuột hay không.
ID nội dung của hình ảnh được sử dụng làm biểu tượng chuột người dùng.
Xác định xem biểu tượng Mouse có hiển thị hay không.
Xác định vị trí của bàn phím trên màn hình.
Xác định kích cỡ của bàn phím trên màn hình.
Mô tả xem liệu bàn phím trên màn hình có hiển thị trên màn hình của người dùng hay không.
Mô tả xem thiết bị hiện tại của người dùng có cảm ứng có sẵn hay không.
Chỉ ra xem người dùng có đang sử dụng một tai nghethực tế ảo hay không.
Phương Pháp
Trả về xem liệu gamepad được cung cấp có hỗ trợ nút tương ứng với được cung cấp hay không.
Trả về một array của Enum.UserInputType gamepad hiện đang kết nối.
Trả về một InputObject mô tả tốc độ gia tốc hiện tại của thiết bị.
Trả về một InputObject mô tả vectơ trọng lực hiện tại của thiết bị.
Trả về một InputObject và một CFrame , mô tả vector xoay hiện tại của thiết bị.
Trả về hiện tại TextBox khách hàng đang tập trung vào.
Trả về xem liệu gamepad với Enum.UserInputType ''gamepadNum'' được cho phép kết nối hay không.
Trả về một array của InputObjects cho tất cả các đầu vào có sẵn trên gamepad được cho, đại diện cho tình trạng nhập cuối cùng của mỗi đầu vào.
Trả về một hình ảnh cho yêu cầu Enum.KeyCode .
Trả về một array của InputObjects được liên kết với keys hiện đang bị nhấn xuống.
Trả về Enum.UserInputType liên quan đến nhập mới nhất của người dùng.
Trả về một array của InputObjects phù hợp với các nút chuột đang được giữ hiện tại.
Trả về thay đổi, bằng像素, vị trí của Mouse người chơi trong khung cuối cùng được render. Chỉ hoạt động nếu chuột được khóa.
Trả vị trí màn hình hiện tại của người chơi Mouse tương quan với góc trên cùng bên trái của màn hình.
Trả về một mảng của gamepads được kết nối và bật để điều hướng GUI theo thứ tự từ trên xuống dưới ưu tiên.
Trả về một chuỗi đại diện cho một phím mà người dùng nên nhấn để nhập một đã cho Enum.KeyCode .
Trả về một array của KeyCodes mà gamepad được gắn với Enum.UserInputType được hỗ trợ.
Xác định xem có nhấn đúng nút cụ thể trên gamepad cụ thể hay không.
Trả về xem liệu key được cho hiện tại có bị giữ hay không.
Trả về xem liệu mouse button được cho hiện tại có bị giữ hay không.
Trả về true nếu gamepad được chỉ định Enum.UserInputType được phép kiểm soát điều hướng GuiObjects .
Xác định vị trí CFrame của tai nghe VR đối với hướng hiện tại của tai nghe mà người dùng đang mặc.
Bộ đặt xem có hay không có thể di chuyển trình duyệt được chỉ định.
Sự Kiện
Bị sa thả khi người dùng di chuyển một thiết bị có accelerometer. Được sử dụng để theo dõi chuyển động thiết bị thực tế trong một trò chơi Roblox.
Bị sa thải khi lực trọng lực thay đổi trên một thiết bị có accelerometer bật - như một thiết bị di động.
Bị sa thả khi người dùng xoay một thiết bị có giroskop.
Bắt lửa khi gamepad được kết nối với khách hàng. Truyền "gamepadNum" của gamepad đã kết nối.
Bắt lửa khi gamepad bị tách khỏi khách hàng. Truyền Enum.UserInputType của gamepad bị tách khỏi.
Bị sa thải khi người dùng bắt đầu tương tác thông qua thiết bị Giao diện Con người - Máy Tính như một chuột hoặc gamepad.
Bị sa thải khi người dùng thay đổi cách họ tương tác thông qua thiết bị Giao diện Con người - Máy tính.
Bắt lửa khi một người dùng ngừng tương tác thông qua thiết bị Giao diện Người-Máy.
Bắt lửa mỗi khi khách hàng yêu cầu nhân vật của họ nhảy.
Bắt lửa khi Enum.UserInputType của khách hàng thay đổi.
- PointerAction(wheel : number,pan : Vector2,pinch : number,gameProcessedEvent : boolean):RBXScriptSignal
Bắt lửa khi người dùng thực hiện một hành động chỉ mục cụ thể (bánh xe, kéo, kéo).
Bị sa thải khi khách hàng mất tập trung vào một TextBox .
Bị sa thải khi khách hàng tập trung vào một TextBox .
- TouchDrag(dragDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Bị bắn khi người dùng thả ngón tay khỏi màn hình trên thiết bị có chạm vào - như màn hình của một thiết bị di động.
- TouchLongPress(touchPositions : Array,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Bị bắn khi người dùng giữ ít nhất một ngón tay trong một thời gian ngắn trên cùng một vị trí màn hình trên một thiết bị được bật chạm - như màn hình của một thiết bị di động.
Bắt lửa khi người dùng di chuyển ngón tay trên thiết bị TouchEnabled như một máy tính bảng hoặc điện thoại thông minh.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Bị bắn khi người dùng kéo ít nhất một ngón tay trên một thiết bị TouchEnabled - như màn hình của một thiết bị di động.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Bị bắn khi một người dùng siết ngón tay vào một thiết bị TouchEnabled - như màn hình của một thiết bị di động.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Bắt lửa khi người dùng xoay hai ngón tay trên một thiết bị TouchEnabled - như màn hình của thiết bị di động.
Bị bắn khi người dùng đặt ngón tay lên một thiết bị có bản lề chạm - như màn hình của một chiếc iPad hoặc iPhone của Apple hoặc một chiếc điện thoại Android của Google.
- TouchSwipe(swipeDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Lửa bùng phát trên một thiết bị TouchEnabled khi người dùng đặt ngón tay của họ xuống trên màn hình, cuộn qua màn hình và nâng ngón tay của họ với tốc độ di chuyển nhất định.
Bị bắn khi người dùng chạm ngón tay vào một thiết bị TouchEnabled - như màn hình của một thiết bị di động.
Bắt lửa khi người dùng nhấn vào thế giới trò chơi trên một thiết bị TouchEnabled - như màn hình của thiết bị di động.
Bắt lửa khi cửa sổ của khách hàng Roblox mất tập trung vào màn hình của người dùng.
Bắt lửa khi cửa sổ của khách hàng Roblox nhận được sự chú ý trên màn hình của người dùng.
Thuộc Tính
AccelerometerEnabled
Thuộc tính này mô tả xem thiết bị của người dùng có có accelerometer hay không
Một accelorometer là một thành phần được tìm thấy trong hầu hết các thiết bị di động mà đo gia tốc (thay đổi tốc độ).
Ví dụ, đoạn mã sau đây minh họa cách kiểm tra xem thiết bị của người dùng có có accelerometer hay không.
local UserInputService = game:GetService("UserInputService")local accelerometerEnabled = UserInputService.AccelerometerEnabledif accelerometerEnabled thenprint("Accelerometer enabled!")elseprint("Accelerometer not enabled!")end
Nếu thiết bị có một accelerometer được bật, bạn có thể nhận được gia tốc hiện tại của nó bằng cách sử dụng chức năng UserInputService:GetDeviceAcceleration() hoặc theo dõi khi gia tốc của thiết bị thay đổi bằng cách sử dụng sự kiện UserInputService.DeviceAccelerationChanged.
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Mẫu mã
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.
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.
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
Thuộc tính này mô tả xem thiết bị đang được sử dụng bởi người dùng có gamepad có sẵn hay không.Nếu gamepad có sẵn, bạn có thể sử dụng UserInputService:GetConnectedGamepads() để lấy lại danh sách gamepad được kết nối.
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Mẫu mã
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.
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
Thuộc tính này mô tả xem thiết bị của người dùng có gyroscope hay không.
Một con quay hồi chuyển là một thành phần được tìm thấy trong hầu hết các thiết bị di động phát hiện hướng và tốc độ quay.
Nếu thiết bị của người dùng có giroskop, bạn có thể sử dụng nó trong trò chơi của mình bằng cách sử dụng chức năng UserInputService:GetDeviceRotation() và sự kiện UserInputService.DeviceRotationChanged.
local UserInputService = game:GetService("UserInputService")local gyroIsEnabled = UserInputService.GyroscopeEnabledif gyroIsEnabled thenprint("Gyroscope is enabled!")elseprint("Gyroscope is not enabled!")end
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Mẫu mã
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.
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
Tính năng này mô tả xem thiết bị của người dùng có bàn phím sẵn không.Thuộc tính này là true khi thiết bị của người dùng có bàn phím có sẵn, và false khi nó không có.
Nó có thể được sử dụng để xác định xem người dùng có bàn phím có sẵn không - có thể là quan trọng nếu bạn muốn kiểm tra xem bạn có thể sử dụng UserInputService:IsKeyDown() hoặc UserInputService:GetKeysPressed() để kiểm tra đầu vào bàn phím.
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Mẫu mã
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.
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
Thuộc tính này xác định cách chuột của người dùng hoạt động dựa trên enum Enum.MouseBehavior. Nó có thể được đặt thành ba giá trị:
- Enum.MouseBehavior.Default — Chuột di chuyển tự do xung quanh màn hình của người dùng.
- Enum.MouseBehavior.LockCenter — Chuột bị khóa và không thể di chuyển khỏi trung tâm của màn hình người dùng.
- Enum.MouseBehavior.LockCurrentPosition — Chuột bị khóa và không thể di chuyển khỏi vị trí hiện tại trên màn hình của người dùng tại thời điểm khóa.
Giá trị của thuộc tính này không ảnh hưởng đến độ nhạy theo dõi chuyển động chuột sự kiện.Ví dụ, GetMouseDelta trả về cùng một vị trí màn hình Vector2 bằng pixel, bất kể liệu chuột có bị khóa hay có thể di chuyển tự do xung quanh màn hình của người dùng.Kết kết quảlà, các kịch bản mặc định như những kịch bản kiểm soát máy ảnh không bị ảnh hưởng bởi tính chất này.
Thuộc tính này bị vô hiệu hóa nếu một GuiButton với Modal bật được kích hoạt là GuiButton.Visible trừ khi nút chuột phải của người chơi đang ở dưới.
Lưu ý rằng, nếu chuột bị khóa, UserInputService.InputChanged vẫn sẽ bắn khi người chơi di chuyển chuột và sẽ đi qua Delta mà chuột đã cố di chuyển.Ngoài ra, nếu người chơi bị đuổi khỏi trò chơi, chuột sẽ được mở khóa bằng lực.
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Mẫu mã
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.
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:
- Mobile camera events, which rely on touch events
- 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.
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
Thuộc tính này xác định độ nhạy của người dùng Mouse .
Độ nhạy xác định mức độ mà một chuyển động của chuột vật lý dịch sang chuyển động của chuột trong trò chơi.Nó có thể được sử dụng để điều chỉnh cách theo dõi sự di chuyển của chuột cảm biến nhạy cảm, như GetMouseDelta , là sự di chuyển của chuột.
Tính chất này không ảnh hưởng đến chuyển động của biểu tượng chuột.Nó cũng không ảnh hưởng đến cài đặt độ nhạy máy ảnh được tìm thấy trong tab Cài đặt của menu Cài đặt của khách hàng, cũng điều chỉnh độ nhạy của sự kiện theo dõi chuyển động chuột.
Thuộc tính này có giá trị tối đa là 10 và giá trị tối thiểu là 0.Một giá trị thấp tương ứng với độ nhạy thấp hơn, và một giá trị cao hơn tương ứng với độ nhạy cao hơn.
Khi độ nhạy là 0, các sự kiện theo dõi chuyển động của chuột vẫn sẽ bắn nhưng tất cả các tham số và tính chất chỉ ra sự thay đổi vị trí chuột sẽ trả về Vector2.new() , hoặc Vector3.new() trong trường hợp InputObject.Delta .Ví dụ, GetMouseDelta sẽ luôn trả về (0, 0).
Mẫu mã
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.
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
Tính năng này mô tả xem thiết bị của người dùng có có sẵn chuột hay không.Thuộc tính này là true khi thiết bị của người dùng có chuột có sẵn, và false khi nó không có.
local UserInputService = game:GetService("UserInputService")if UserInputService.MouseEnabled thenprint("The user's device has an available mouse!")elseprint("The user's device does not have an available mouse!")end
Quan trọng là phải kiểm tra điều này trước khi sử dụng chức năng chuột UserInputService như UserInputService:GetMouseLocation() .
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Mẫu mã
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.
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
Thuộc tính MouseIcon xác định hình ảnh được sử dụng làm điểm chỉ.Nếu trống, một mũi tên mặc định được sử dụng.Trong khi con trỏ lướt qua các đối tượng UI nhất định như một ImageButton , TextButton , TextBox hoặc ProximityPrompt , hình ảnh này sẽ bị thay thế và bị bỏ qua tạm thời.
Để ẩn hoàn toàn con trỏ, hãy không sử dụng hình ảnh trong suốt. Thay vào đó, hãy đặt UserInputService.MouseIconEnabled thành false.
Mẫu mã
This example changes the user mouse icon to look like a dragon image.
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
Tính chất này xác định xem biểu tượng Mouse có hiển thị khi true biểu tượng của chuột hiển thị, khi false nó không.
Ví dụ, đoạn mã bên dưới che đi biểu tượng của chuộttrỏ.
local UserInputService = game:GetService("UserInputService")UserInputService.MouseIconEnabled = false
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Mẫu mã
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.
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
Thuộc tính này mô tả vị trí của bàn phím trên màn hình bằng pixel. Vị trí của bàn phím là Vector2.new(0, 0) khi nó không hiển thị.
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript , hoặc Script với RunContext được đặt thành Enum.RunContext.Client .
Xem thêm OnScreenKeyboardVisible và OnScreenKeyboardSize .
Mẫu mã
This example prints the position of the player's on-screen keyboard.
local UserInputService = game:GetService("UserInputService")
print(UserInputService.OnScreenKeyboardPosition)
OnScreenKeyboardSize
Thuộc tính này mô tả kích thước của bàn phím trên màn hình bằng pixel. Kích thước của bàn phím là Vector2.new(0, 0) khi nó không hiển thị.
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript , hoặc Script với RunContext được đặt thành Enum.RunContext.Client .
Xem thêm OnScreenKeyboardVisible và OnScreenKeyboardPosition .
OnScreenKeyboardVisible
Tính năng này mô tả xem có bàn phím trên màn hình hiện đang hiển thị trên màn hình của người dùng hay không.
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript , hoặc Script với RunContext được đặt thành Enum.RunContext.Client .
Xem thêm OnScreenKeyboardSize và OnScreenKeyboardPosition .
TouchEnabled
Tính năng này mô tả xem thiết bị hiện tại của người dùng có cảm ứng có sẵn hay không.
Thuộc tính được sử dụng để xác định xem thiết bị của người dùng có màn hình cảm ứng hay không, và do đó sự kiện chạm sẽ bắt lửa.Nếu TouchEnabled là true, bạn có thể sử dụng sự kiện UserInputService như UserInputService.TouchStarted và UserInputService.TouchEnded để theo dõi khi một người dùng bắt đầu và ngừng chạm vào màn hình của thiết bị của họ.
Khối mã dưới đây in ra xem thiết bị của người dùng có màn hình cảm ứng hay không.
local UserInputService = game:GetService("UserInputService")if UserInputService.TouchEnabled thenprint("The user's device has a touchscreen!")elseprint("The user's device does not have a touchscreen!")end
Xem thêm:
Mẫu mã
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:
- Mobile camera events, which rely on touch events
- 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.
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
Thuộc tính này mô tả xem người dùng có đang sử dụng thiết bị thực tế ảo (VR) hay không.
Nếu một thiết bị VR được bật, bạn có thể tương tác với vị trí và chuyển động của nó thông qua các chức năng như UserInputService:GetUserCFrame().Bạn cũng có thể phản ứng với chuyển động của thiết bị VR bằng sự kiện UserInputService.UserCFrameChanged.
local UserInputService = game:GetService("UserInputService")local isUsingVR = UserInputService.VREnabledif isUsingVR thenprint("User is using a VR headset!")elseprint("User is not using a VR headset!")end
Vì UserInputService chỉ là bên khách, tính chất này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Mẫu mã
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.
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
Phương Pháp
GamepadSupports
Chức năng này trả về xem liệu gamepad được cung cấp có hỗ trợ nút tương ứng với được cho hay không.Chức năng này được sử dụng để xác định các đầu vào gamepad hợp lệ.
Để xác định gamepad nào được kết nối, hãy sử dụng .
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType của gamepad.
The Enum.KeyCode của nút trong câu hỏi.
Lợi Nhuận
Liệu gamepad được cung cấp có hỗ trợ nút tương ứng với nút được cho Enum.KeyCode hay không.
Mẫu mã
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".
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
Chức năng này trả về một mảng của Enum.UserInputType gamepad hiện được kết nối.Nếu không có gamepad nào kết nối, mảng này sẽ trống.Ngoài ra, nó chỉ trả về các đối tượng UserInputType là gamepad.Ví ví dụ / trường hợp, sự kiện này sẽ trả lại một đối tượng Gamepad1 kết nối nhưng không phải là đối tượng Bàn phím.
Ví dụ, đoạn mã sau đây truy xuất các gamepad kết nối và lưu chúng trong biến có tên là connectedGamepads.
local UserInputService = game:GetService("UserInputService")local connectedGamepads = UserInputService:GetConnectedGamepads()
Để kiểm tra xem gamepad cụ thể có kết nối hay không, hãy sử dụng UserInputService:GetGamepadConnected() .
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Lợi Nhuận
Một mảng của UserInputTypes phù hợp với gamepad được kết nối với thiết bị của người dùng.
Mẫu mã
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.
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
Chức năng GetDeviceAcceleration xác định tốc độ gia tốc hiện tại của thiết bị người dùng.Nó trả về một InputObject mô tả tốc độ gia tốc hiện tại của thiết bị.
Để có hiệu quả, thiết bị của người dùng phải có accelerometer được bật.Để kiểm tra xem thiết bị của người dùng có bật kích hoạt accelorometer hay không, bạn có thể kiểm tra thuộc tính UserInputService.AccelerometerEnabled.
Nếu bạn muốn theo dõi khi thay đổi tốc độ gia tốc của thiết bị người dùng thay vào đó, bạn có thể sử dụng sự kiện UserInputService.DeviceAccelerationChanged.
Vì nó chỉ bắn lokal, nó chỉ có thể được sử dụng trong một LocalScript .
Lợi Nhuận
Mẫu mã
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!
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
Chức năng này trả về một InputObject mô tả vectơ trọng lực hiện tại của thiết bị.
Vectơ trọng lực được xác định bởi hướng của thiết bị so với lực trọng lực thực tế.Ví ví dụ / trường hợp, nếu một thiết bị hoàn toàn thẳng đứng (chân dung), vector trọng lực là Vector3.new(0, 0, -9.18) .Nếu bên trái của thiết bị chỉ vào xuống, vector là Vector3.new(9.81, 0, 0).Cuối cùng, nếu phía sau của thiết bị chỉ vào xuống, vector là Vector3.new(0, -9.81, 0).
Chức năng này có thể được sử dụng để bật khả năng ảnh hưởng hoặc kiểm soát trọng lực của người dùng trong trò chơi hoặc di chuyển các đối tượng trong trò chơi như một quả bóng.
Tốc độ rơi chỉ được theo dõi đối với người chơi sử dụng thiết bị có giroscope bật - như thiết bị di động.
Để kiểm tra xem thiết bị của người dùng có bật khởi động giroscope hay không, hãy kiểm tra giá trị của UserInputService.GyroscopeEnabled .Nếu thiết bị có giroskop bật, bạn cũng có thể sử dụng sự kiện UserInputService.DeviceGravityChanged để theo dõi khi lực trọng lực trên thiết bị của người dùng thay đổi.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Lợi Nhuận
Mẫu mã
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.
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
Chức năng này trả về một InputObject và một CFrame mô tả vector xoay hiện tại của thiết bị.
Điều này được kích hoạt bằng một InputObject.Thuộc tính Vị trí của đối tượng nhập là một Enum.InputType.Gyroscope theo dõi tổng quay trong mỗi trục thiết bị địa phương.
Việc xoay thiết bị chỉ có thể được theo dõi trên các thiết bị có gyroscope .
Vì chức năng này bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Lợi Nhuận
Một tuple chứa hai thuộc tính:
- Thuộc tính delta mô tả lượng xoay cuối cùng đã xảy ra
- CFrame là sự xoay hiện tại của thiết bị so với khung tham chiếu mặc định của nó.
Mẫu mã
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!
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
Chức năng này trả về TextBox khách hàng hiện đang tập trung vào.Một TextBox có thể được chọn bằng tay bởi người dùng, hoặc lựa chọn có thể bị buộc bằng cách sử dụng chức năng TextBox:CaptureFocus().Nếu không có TextBox được chọn, chức năng này sẽ trả về nil .
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm
Lợi Nhuận
GetGamepadConnected
Chức năng này trả về xem liệu gamepad với địa chỉ Enum.UserInputType được kết nối với khách hàng hay không.
Nó có thể được sử dụng để kiểm tra xem gamepad cụ thể, chẳng hạn như 'Gamepad1' có kết nối với thiết bị của khách hàng hay không.
Để lấy lại danh sách tất cả các gamepad kết nối, hãy sử dụng UserInputService:GetConnectedGamepads() .
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType của gamepad trong câu hỏi.
Lợi Nhuận
Liệu gamepad được kết nối với Enum.UserInputType có được kết nối hay không.
Mẫu mã
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.
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
Chức năng này trả về một mảng của InputObjects cho tất cả các đầu vào có sẵn trên gamepad Enum.UserInputType được cho, đại diện cho tình trạng nhập cuối cùng của mỗi đầu vào.
Để tìm UserInputTypes của gamepad kết nối, hãy sử dụng UserInputService:GetConnectedGamepads() .
Vì chức năng này chỉ bắn lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType tương ứng với gamepad trong câu hỏi.
Lợi Nhuận
Một mảng của InputObjects đại diện cho tình trạng hiện tại của tất cả các đầu vào có sẵn cho gamepad đã cho.
GetImageForKeyCode
Phương pháp này nhận Enum.KeyCode yêu cầu và trả lại hình ảnh liên quan cho thiết bị gamepad được kết nối hiện tại (giới hạn ở Xbox, PlayStation và Windows).Điều này có nghĩa là nếu điều khiển kết nối là điều khiển Xbox One, người dùng sẽ thấy tài sản Xbox.Tương tự, nếu thiết bị kết nối là điều khiển PlayStation, người dùng sẽ thấy tài sản của PlayStation.Nếu bạn muốn sử dụng tài sản tùy chỉnh, xem GetStringForKeyCode() .
Tham Số
The Enum.KeyCode để lấy hình ảnh liên quan.
Lợi Nhuận
ID tài sản hình ảnh trả về.
Mẫu mã
This API returns the requested image for the given Enum.KeyCode.
local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappedIconImage = UserInputService:GetImageForKeyCode(key)
imageLabel.Image = mappedIconImage
GetKeysPressed
Chức năng này trả về một mảng của InputObjects liên quan đến các phím đang được nhấn xuống hiện tại.
Danh sách này có thể được lặp qua để xác định các phím đang được nhấn, bằng cách sử dụng các giá trị InputObject.KeyCode.
Để kiểm tra xem có phím cụ thể đang được nhấn hay không, hãy sử dụng UserInputService:IsKeyDown() .
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Lợi Nhuận
Một mảng của InputObjects liên quan đến các phím đang được nhấn hiện tại.
Mẫu mã
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.
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
Chức năng này trả về 'Enum.UserInputType` liên quan đến nhập mới nhất của người dùng.
Ví dụ, nếu lần nhập trước của người dùng đã nhấn phím cách, Enum.UserInputType trả về sẽ là 'Bàn phím' .
Sự kiện UserInputService.LastInputTypeChanged có thể được sử dụng để theo dõi khi sử dụng lần cuối cùng Enum.UserInputType bởi người dùng thay đổi.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Lợi Nhuận
Các Enum.UserInputType liên quan đến nhập mới nhất của người dùng.
Mẫu mã
This example gets the last input type and indicates if it was keyboard input.
local UserInputService = game:GetService("UserInputService")
local lastInput = UserInputService:GetLastInputType()
if lastInput == Enum.UserInputType.Keyboard then
print("Most recent input was via keyboard")
end
GetMouseButtonsPressed
Chức năng này trả về một mảng của InputObjects tương ứng với các nút chuột đang được nhấn hiện tại.
Nút chuột được theo dõi bởi chức năng này bao gồm:
<td>Mô tả</td></tr></thead><tr><td>Nút chuột1</td><td>Nút chuột bên trái.</td></tr><tr><td>Nút chuột 2</td><td>Nút chuột phải.</td></tr><tr><td>Nút chuột 3</td><td>Nút chuột giữa.</td></tr>
Tên |
---|
Nếu người dùng không nhấn bất kỳ nút chuột nào xuống khi chức năng được gọi, nó sẽ trả về một mảng trống.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Lợi Nhuận
Một mảng của InputObjects phù hợp với các nút chuột đang được giữ hiện tại.
Mẫu mã
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.
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
Chức năng này trả về thay đổi, bằng pixel, vị trí của người chơi Mouse trong khung cuối cùng được hiển thị như một Vector2 .Chức năng này chỉ hoạt động nếu chuột đã bị khóa bằng cách sử dụng thuộc tính UserInputService.MouseBehavior.Nếu chuột chưa bị khóa, các giá trị trả về Vector2 sẽ là không.
Độ nhạy của chuột, được xác định trong cài đặt của khách hàng và UserInputService.MouseDeltaSensitivity, sẽ ảnh hưởng đến kết quả.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Lợi Nhuận
Thay đổi trong chuyển động của chuột.
Mẫu mã
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.
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:
- Mobile camera events, which rely on touch events
- 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.
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
Chức năng này trả về một Vector2 đại diện cho vị trí màn hình hiện tại của người chơi Mouse trong điểm ảnh so với góc trên cùng bên trái.Điều này không tính đến Enum.ScreenInsets ; để có được các chỉnh sáng bên trái và bên phải trên cùng, hãy gọi GuiService:GetGuiInset() .
Nếu vị trí của con trỏ chuột nằm ngoài màn hình hoặc thiết bị của người chơi không có chuột, giá trị trả về sẽ không được xác định.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Lợi Nhuận
Mẫu mã
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.
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
Chức năng này trả về một mảng gamepad UserInputTypes được kết nối và bật để điều hướng GUI.Danh sách này ở trong trật tự giảm dần về ưu tiên, có nghĩa là nó có thể được lặp lại để xác định gamepad nào nên có điều khiển điều hướng.
Liệu gamepad kết nối có phải là gamepad điều hướng chỉ xác định gamepad nào (các gamepad) kiểm soát các GUI điều hướng.Điều này không ảnh hưởng đến điều khiển điều hướng.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
- UserInputService:SetNavigationGamepad() , để bật hoặc tắt gamepad cho điều hướng GUI
- UserInputService:IsNavigationGamepad() , để xác minh xem gamepad có được bật cho điều hướng GUI hay không
- UserInputService:GetConnectedGamepads() , để trả lại tất cả các gamepad được kết nối bất kể điều hướng GUI
Lợi Nhuận
Một mảng của UserInputTypes có thể được sử dụng cho điều hướng GUI, theo thứ tự ưu tiên giảm dần.
GetStringForKeyCode
Nhận chuỗi cho mã khóa trả về một chuỗi đại diện cho một phím mà người dùng nên nhấn để nhập một đã cho Enum.KeyCode , lưu ý bố trí bàn phím của họ.Đối với mã chìa khóa cần có một số chỉnh sửa được giữ, chức năng này trả về chìa khóa cần được nhấn cùng với chỉnh sửa.Xem các ví dụ dưới đây để có thêm lời giải thích.
Khi sử dụng Roblox với bố trí bàn phím không phải là QWERTY, mã khóa được định vị tương đương với vị trí QWERTY tương ứng.Ví dụ, nhấn A trên bàn phím AZERTY kết quả là Enum.KeyCode.Q .Bản đồ hóa này có thể dẫn đến thông tin không phù hợp trên các yếu tố giao diện người dùng trải nghiệm.Ví dụ, "Nhấn M để mở bản đồ" không chính xác trên bàn phím AZERTY; nó sẽ cần phải là "Nhấn ? để mở bản đồ" có cùng vị trí với M trên QWERTY.Chức năng này giải quyết vấn đề này bằng cách cung cấp chìa khóa thực sẽ được nhấn khi sử dụng các bố trí bàn phím không phải là QWERTY.
local UserInputService = game:GetService("UserInputService")local textLabel = script.Parentlocal mapKey = Enum.KeyCode.MtextLabel.Text = "Press " .. UserInputService:GetStringForKeyCode(mapKey) .. " to open the map"
Ví dụ trên Bàn phím QWERTY
<th>Trả giá trị trở lại</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 Như vậy</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.Tại</code></td><td><code>2</code> vì <code>@</code> được gõ với <kbd>Shift</kbd><kbd>2</kbd></td></tr></tbody>
Mã khóa |
---|
Ví dụ trên Bàn phím AZERTY
<th>Trả giá trị trở lại</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 Như vậy</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.Tại</code></td><td><code>É</code></td></tr></tbody>
Mã khóa |
---|
Sử dụng gamepad
GetStringForKeyCode() trả về chuỗi bản đồ cho Enum.KeyCode gamepad gần đây nhất đã kết nối.Nếu điều khiển kết nối không được hỗ trợ, chức năng trả về chuỗi chuyển đổi mặc định cho mã yêu cầu.
Ví dụ sau đây cho thấy cách bạn có thể đánh dấu tài sản tùy chỉnh cho ButtonA :
local UserInputService = game:GetService("UserInputService")local imageLabel = script.Parentlocal key = Enum.KeyCode.ButtonAlocal mappings = {ButtonA = "rbxasset://BUTTON_A_ASSET", -- Replace with the desired ButtonA assetButtonCross = "rbxasset://BUTTON_CROSS_ASSET" -- Replace with the desired ButtonCross asset}local mappedKey = UserInputService:GetStringForKeyCode(key)local image = mappings[mappedKey]imageLabel.Image = image
Bản đồ gamepad
Các mã phím điều hướng không có sự khác biệt dựa trên thiết bị.Enum.KeyCode.ButtonSelect có hành vi khác nhau một chút trong một số trường hợp.Sử dụng cả hai bản đồ PlayStation để đảm bảo người dùng nhìn thấy các nút chính xác.
<th>Giá trị trả lại của PlayStation</th><th>Giá trị trả lại Xbox</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonA</code></td><td><code>Nút Cross</code></td><td><code>Nút A</code></td></tr><tr><td><code>Enum.KeyCode.ButtonB</code></td><td><code>Vòng Nút</code></td><td><code>Nút B</code></td></tr><tr><td><code>Enum.KeyCode.ButtonX</code></td><td><code>Nút Vuông</code></td><td><code>Cái nútX</code></td></tr><tr><td><code>Enum.KeyCode.ButtonY</code></td><td><code>Nút tam giác</code></td><td><code>NútY</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><code>Nút L1</code></td><td><code>Nút LB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL2</code></td><td><code>Nút L2</code></td><td><code>NútLT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL3</code></td><td><code>Nút L3</code></td><td><code>NútLS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><code>Nút R1</code></td><td><code>NútRB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR2</code></td><td><code>Nút R2</code></td><td><code>Nút RT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><code>Nút R3</code></td><td><code>Nút RRS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonBắt đầu</code></td><td><code>Tùy chọn nút</code></td><td><code>Nút Bắt đầu</code></td></tr><tr><td><code>Enum.KeyCode.Nút chọn</code></td><td><code>ButtonTouchpad</code> và <code>ButtonShare</code></td><td><code>NútChọn</code></td></tr></tbody>
Mã khóa |
---|
Hình ảnh hệ thống cho KeyCodes
Khi sử dụng một Enum.KeyCode có thể được biểu diễn tốt hơn như một hình ảnh, chẳng hạn như cho một ImageLabel trong giao diện người dùng, bạn có thể sử dụng các biểu tượng di sản sau.Tuy nhiên, được khuyến nghị rằng bạn nên sử dụng GetImageForKeyCode() như một phương pháp hiện đại hơn, chéo nền tảng để lấy lại các biểu tượng điều khiển Xbox và PlayStation.
<th>Hình ảnh</th><th>ID tài sản</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonX</code></td><td><img src="../../../assets/scripting/controls/xboxX.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxX.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonY</code></td><td><img src="../../../assets/scripting/controls/xboxY.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/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/Controls/xboxA.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonB</code></td><td><img src="../../../assets/scripting/controls/xboxB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxB.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadLeft</code></td><td><img src="../../../assets/scripting/controls/dpadLeft.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadLeft.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadRight</code></td><td><img src="../../../assets/scripting/controls/dpadRight.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadRight.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadUp</code></td><td><img src="../../../assets/scripting/controls/dpadUp.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadUp.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadDown</code></td><td><img src="../../../assets/scripting/controls/dpadDown.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadDown.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonSelect</code></td><td><img src="../../../assets/scripting/controls/xboxView.png" width="24"></img></td><td><code>rbxasset://textures/ui/Điều khiển/xboxView.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonBắt đầu</code></td><td><img src="../../../assets/scripting/controls/xboxmenu.png" width="24"></img></td><td><code>rbxasset://textures/ui/Điều khiển/xboxmenu.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><img src="../../../assets/scripting/controls/xboxLB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLB.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><img src="../../../assets/scripting/controls/xboxRB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/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/Điều khiển/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/Controls/xboxRT.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL3</code></td><td><img src="../../../assets/scripting/controls/xboxLS.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLS.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><img src="../../../assets/scripting/controls/xboxRS.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRS.png</code></td></tr><tr><td><code>Enum.KeyCode.Thumbstick1</code></td><td><img src="../../../assets/scripting/controls/xboxLSDirectional.png" width="24"></img></td><td><code>rbxasset://textures/ui/Điều khiển/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/Điều khiển/xboxRSDirectional.png</code></td></tr><tr><td><code>Enum.KeyCode.Backspace</code></td><td><img src="../../../assets/scripting/controls/backspace.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/backspace.png</code></td></tr><tr><td><code>Enum.KeyCode.Return</code></td><td><img src="../../../assets/scripting/controls/return.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/return.png</code></td></tr><tr><td><code>Enum.KeyCode.LeftShift</code></td><td><img src="../../../assets/scripting/controls/shift.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/shift.png</code></td></tr><tr><td><code>Enum.KeyCode.RightShift</code></td><td><img src="../../../assets/scripting/controls/shift.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/shift.png</code></td></tr><tr><td><code>Enum.KeyCode.Tab</code></td><td><img src="../../../assets/scripting/controls/tab.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/tab.png</code></td></tr><tr><td><code>Enum.KeyCode.Apostrophe</code></td><td><img src="../../../assets/scripting/controls/apostrophe.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/apostrophe.png</code></td></tr><tr><td><code>Enum.KeyCode.Comma</code></td><td><img src="../../../assets/scripting/controls/comma.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/comma.png</code></td></tr><tr><td><code>Enum.KeyCode.Backquote</code></td><td><img src="../../../assets/scripting/controls/graveaccent.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/graveaccent.png</code></td></tr><tr><td><code>Enum.KeyCode.Period</code></td><td><img src="../../../assets/scripting/controls/period.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/period.png</code></td></tr><tr><td><code>Enum.KeyCode.Space</code></td><td><img src="../../../assets/scripting/controls/spacebar.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/spacebar.png</code></td></tr></tbody>
Mã khóa |
---|
Tham Số
Lợi Nhuận
GetSupportedGamepadKeyCodes
Chức năng này trả về một mảng của KeyCodes mà gamepad được gắn với Enum.UserInputType có hỗ trợ.
Chức năng này có thể được sử dụng để xác định các KeyCodes nào được hỗ trợ và không được hỗ trợ bởi gamepad kết nối.Để xác định xem có hỗ trợ một KeyCode cụ thể hay không, hãy sử dụng UserInputService:GamepadSupports() .
Nếu gọi trên một gamepad không tồn tại hoặc không kết nối, chức năng này sẽ trả về một mảng trống.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType của gamepad.
Lợi Nhuận
Mẫu mã
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.
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
Chức năng này kiểm tra xem có nhấn đúng nút cụ thể trên gamepad cụ thể hay không.Nó trả về true nếu gamepad có được nhấn xuống button đã được định, nếu không, nó trả về giả mạo.
Các loại đầu vào người dùng hợp lệ
Bàn game được chỉ định phải là một trong các giá trị enum UserInputType sau:
<tr><td>Enum.UserInputType.Gamepad1-8</td></tr>
Tên |
---|
Mã hóa chính xác KeyCodes
Nút được chỉ định phải là một trong các giá trị enum KeyCodes sau:
<tr><td>Enum.KeyCode.ButtonX</td></tr><tr><td>Enum.KeyCode.ButtonY</td></tr><tr><td>Enum.KeyCode.ButtonA</td></tr><tr><td>Enum.KeyCode.ButtonB</td></tr><tr><td>Enum.KeyCode.ButtonR1</td></tr><tr><td>Enum.KeyCode.ButtonL1</td></tr><tr><td>Enum.KeyCode.ButtonR2</td></tr><tr><td>Enum.KeyCode.ButtonL2</td></tr><tr><td>Enum.KeyCode.ButtonR3</td></tr><tr><td>Enum.KeyCode.ButtonL3</td></tr><tr><td>Enum.KeyCode.ButtonBắt đầu</td></tr><tr><td>Enum.KeyCode.Nút chọn</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.DPadXuống</td></tr>
Tên |
---|
Nó có thể được sử dụng để kiểm tra xem liệu nút cụ thể, chẳng hạn như A, có được giữ hay không. Ví dụ:
local UserInputService = game:GetService("UserInputService")local button = Enum.KeyCode.ButtonAlocal gamepad = Enum.UserInputType.Gamepad1local isButtonHeld = UserInputService:IsGamepadButtonDown(gamepad, button)
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
- UserInputService:IsKeyDown() - Một phương pháp tương tự với một sử dụng khác: Để kiểm tra xem có được nhấn key trên keyboard không.
Tham Số
The Enum.UserInputType của gamepad được cho.
The Enum.KeyCode của nút được chỉ định.
Lợi Nhuận
Liệu nút gamepad được chỉ định trên gamepad được cho là được nhấn hay không.
Mẫu mã
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.
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
Chức năng này trả về xem người dùng có đang giữ phím liên quan đến Enum.KeyCode đã cho hay không.Nó trả về true nếu phím được chỉ định được nhấn hoặc false nếu nó không được nhấn.
Nó có thể được sử dụng để kiểm tra xem có chìa khóacụ thể, chẳng hạn như thanh không gian, đang được nhấn hay không. Ví dụ:
local UserInputService = game:GetService("UserInputService")local spaceHeld = UserInputService:IsKeyDown(Enum.KeyCode.Space)
Để lấy lại danh sách tất cả các phím được nhấn bởi người dùng, hãy sử dụng chức năng UserInputService:GetKeysPressed().
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
- Enum.UserInputType.IsGamepadButtonDown - Một sự kiện tương tự với một sử dụng khác: Để kiểm tra xem có được nhấn button trên gamepad không.
Tham Số
The Enum.KeyCode của chìa khóa.
Lợi Nhuận
Liệu chìa khóa được chỉ định đang được giữ xuống.
Mẫu mã
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.
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
Chức năng này nhận một nút chuột Enum.UserInputType và trả về một bool cho thấy liệu nó hiện đang được nhấn hay không.
Nút chuột kiểm tra phụ thuộc vào giá trị Enum.UserInputType được chuyển cho chức năng như một tham số. Ví dụ:
local UserInputService = game:GetService("UserInputService")local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript."
Tham Số
The Enum.UserInputType của nút chuột.
Lợi Nhuận
Liệu nút chuột được cho đã được giữ hiện tại hay không.
Mẫu mã
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:
- Mobile camera events, which rely on touch events
- 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.
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
Chức năng này trả về nếu gamepad được chỉ định được phép kiểm soát Điều hướng và Lựa chọn .
Nếu bạn muốn thiết lập một gamepad điều hướng, bạn có thể sử dụng UserInputService:SetNavigationGamepad() . Bạn cũng có thể sử dụng UserInputService:GetNavigationGamepads() để lấy danh sách tất cả các gamepad điều hướng.
Ví dụ, mã dưới đây kiểm tra xem gamepad1 có phải là gamepad điều hướng không:
local UserInputService = game:GetService("UserInputService")if UserInputService:IsNavigationGamepad(UserInputType.Gamepad1) thenprint("Gamepad is a navigation gamepad!")elseprint("Gamepad is not a navigation gamepad!")end
Một danh sách tất cả các gamepad kết nối, bất kể điều hướng có thể được truy xuất bằng cách sử dụng `UserInput/GetConnectedGamepads.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType của gamepad được chỉ định.
Lợi Nhuận
Whether gamepad được chỉ định là gamepad điều hướng.
RecenterUserHeadCFrame
Chức năng này làm trung tâm lại CFrame của tai nghe VR về hướng hiện tại của tai nghe mà người dùng đang mặc.Điều này có nghĩa là hướng hiện tại của tai nghe được đặt thành CFrame.new() .
Sử dụng chức năng này để di chuyển tai nghe CFrame vào trung tâm khu vực chơi nếu có vẻ như nó ở một khoảng cách kỳ lạ.
Hành vi này giống như chức năng VRService , VRService:RecenterUserHeadCFrame() .
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Lợi Nhuận
Mẫu mã
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.
local UserInputService = game:GetService("UserInputService")
UserInputService:RecenterUserHeadCFrame()
SetNavigationGamepad
Chức năng SetNavigationGamepad xác định xem gamepad được chỉ định Enum.UserInputType có thể di chuyển trình duyệt GUI không.Một gamepad được phép di chuyển trình duyệt GUI được coi là gamepad điều hướng.
Nếu argument được bật được truyền như true , Gamepad có thể di chuyển trình duyệt GUI.Nếu argument là false, Gamepad không thể di chuyển trình duyệt GUI.
Nếu bạn muốn kiểm tra xem Gamepad được chỉ định có được đặt làm gamepad điều hướng hay không, bạn có thể sử dụng chức năng UserInputService:IsNavigationGamepad().Bạn cũng có thể sử dụng UserInputService:GetNavigationGamepads() để lấy lại danh sách tất cả các gamepad điều hướng.
Vì UserInputService chỉ là bên khách, chức năng này chỉ có thể được sử dụng trong LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType của gamepad được chỉ định.
Liệu gamepad được chỉ định có thể di chuyển trình duyệt GUI không.
Lợi Nhuận
Mẫu mã
This example sets Gamepad1 as a navigation gamepad by passing Enum.UserInputType.Gamepad1 and true as arguments.
local UserInputService = game:GetService("UserInputService")
UserInputService:SetNavigationGamepad(Enum.UserInputType.Gamepad1, true)
Sự Kiện
DeviceAccelerationChanged
Sự kiện DeviceAccelerationChanged bắt lửa khi người dùng di chuyển một thiết bị có accelerometer.
Một accelorometer là một thành phần được tìm thấy trong hầu hết các thiết bị di động mà đo gia tốc (thay đổi tốc độ).
Để xác định xem thiết bị của người dùng có bật accelerometer hay không, xem UserInputService.AccelerometerEnabled .
Sự kiện này có thể được sử dụng để theo dõi chuyển động của một thiết bị có accelerometer.Một ví dụ sử dụng bao gồm di chuyển nhân vật người chơi khi một thiết bị di động tăng tốc.
Ngoài ra, sự kiện này có thể được sử dụng cùng với UserInputService:GetDeviceAcceleration() để xác định chuyển động hiện tại của thiết bị người dùng nếu thiết bị có accelerometer.
Sự kiện này chỉ bắt lửa địa phương - có nghĩa là chỉ người chơi có thiết bị di chuyển có thể sử dụng sự kiện và nó sẽ chỉ hoạt động trong một LocalScript .
Tham Số
Một InputObject , với một UserInputType của 'Accelerometer' , và Position cho thấy lực trọng lực trên mỗi trục thiết bị địa phương.
Mẫu mã
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.
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
Sự kiện UserInputService.DeviceGravityChanged xảy ra khi trọng lực của thiết bị thay đổi Vector3 trên một thiết bị có accelerometer.
Vectơ trọng lực của một thiết bị đại diện cho lực trọng lực trên mỗi trục X, Y và Z của thiết bị.Trong khi trọng lực không bao giờ thay đổi, lực mà nó tác động lên mỗi trục thay đổi khi thiết bị quay và thay đổi hướng.Giá trị lực được áp dụng trên mỗi trục là một vector đơn vị dao động từ -1 đến 1.
Một accelorometer là một thành phần được tìm thấy trong hầu hết các thiết bị di động mà đo gia tốc (thay đổi tốc độ).
Sự kiện này có thể được sử dụng để xác định hướng thực tế của lực trọng lực trên thiết bị của người dùng.Nó thậm chí có thể được sử dụng để mô phỏng lực trọng lực trên thiết bị của người dùng trong trò chơi, như trên các đối tượng trong trò chơi (xem ví dụ dưới đây).
Để kiểm tra xem thiết bị của người dùng có bật kích hoạt accelorometer hay không, xem UserInputService.AccelerometerEnabled .Nếu thiết bị có một accelerometer được bật, bạn có thể sử dụng chức năng UserInputService:GetDeviceGravity() để lấy lực trọng lực hiện tại trên thiết bị của người dùng.
Tham Số
Một InputObject , với một tính năng InputObject.Position cho thấy lực trọng lực trên mỗi trục thiết bị địa phương.Vị trí này có thể được sử dụng như một hướng để xác định hướng trọng lực so với thiết bị.
Mẫu mã
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.
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.
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
Sự kiện DeviceRotationChanged xảy ra khi một người dùng xoay một thiết bị có giroskop.
Một con quay hồi chuyển là một thành phần được tìm thấy trong hầu hết các thiết bị di động phát hiện hướng và tốc độ quay.
Sự kiện có ích khi theo dõi hướng của thiết bị và cách thay đổi khi người dùng xoay thiết bị của họ.Để xác định vị trí xoay thiết bị hiện tại, bạn có thể sử dụng chức năng UserInputService:GetDeviceRotation().
Để kiểm tra xem thiết bị của người dùng có bật khả năng giroskop hay không, và sự kiện này sẽ bắt lửa, xem UserInputService.GyroscopeEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Tham Số
Một InputObject cung cấp thông tin về sự xoay của thiết bị. đại diện cho vị trí xoay mới a đại diện cho giá trị vị trí xoay thay đổi và đại diện cho sự thay đổi vị trí xoay trong một giá trị vị trí.
Mẫu mã
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.
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.
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
Sự kiện GamepadConnected bắt lửa khi gamepad được kết nối với khách hàng.
Vì một trò chơi Roblox hỗ trợ nhiều điều khiển, sự kiện này hữu ích khi kết hợp với sự kiện UserInputService.GamepadDisconnected để theo dõi các điều khiển/gamepad nào đang hoạt động.Bạn cũng có thể sử dụng UserInputService:GetConnectedGamepads() để tìm gamepad chính xác để sử dụng.
Ví dụ sau đây minh họa một ví dụ sử dụng khi gamepad được kết nối với khách hàng.
local UserInputService = game:GetService("UserInputService")
local function GamepadConnected(gamepad)
print("Player has plugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadConnected:Connect(GamepadConnected)
Nếu bạn muốn xem các thiết bị nào được kết nối, bạn có thể sử dụng chức năng UserInputService:GetConnectedGamepads().
Vì sự kiện này bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType của gamepad kết nối.
GamepadDisconnected
Sự kiện GamepadDisconnected bắt lửa khi gamepad bị tách kết nối.
Vì một trò chơi Roblox hỗ trợ nhiều điều khiển, sự kiện này hữu ích khi kết hợp với sự kiện UserInputService.GamepadConnected để theo dõi các điều khiển/gamepad nào đang hoạt động.Bạn cũng có thể sử dụng UserInputService:GetConnectedGamepads() để tìm gamepad chính xác để sử dụng.
Ví dụ sau đây minh họa một ví dụ sử dụng khi một gamepad bị tách khỏi khách hàng.
local UserInputService = game:GetService("UserInputService")
local function GamepadDisconnected(gamepad)
print("Player has unplugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadDisconnected:Connect(GamepadDisconnected)
Vì sự kiện này bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
The Enum.UserInputType của gamepad bị tách kết nối.
InputBegan
Sự kiện InputBegan bắt lửa khi một người dùng bắt đầu tương tác thông qua thiết bị Giao diện Con người - Máy tính (nhấn nút chuột xuống, chạm bắt đầu, nút bàn phím xuống, v.v.).
Nó có thể được sử dụng để theo dõi khởi đầu của tương tác người dùng, chẳng hạn như khi một người dùng lần đầu tiên tương tác với một yếu tố GUI, một gamepad, v.v.Nó không thu được chuyển động bánh xe chuột.
Sự kiện này có thể được sử dụng cùng với UserInputService.InputChanged và UserInputService.InputEnded để theo dõi khi nào bắt đầu nhập, thay đổi và kết thúc của người dùng.
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Tham Số
Một ví ví dụ / trường hợp, chứa thông tin về nhập của người dùng.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
The following example demonstrates one of many usage examples of handling user input from InputBegan depending on its type.
-- 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
Sự kiện InputChanged bắt lửa khi người dùng thay đổi cách họ tương tác thông qua thiết bị Giao diện Con người - Máy tính (nhấn nút chuột xuống, chạm bắt đầu, nhấn nút bàn phím xuống, v.v.).
Để bỏ qua các sự kiện được xử lý tự động bởi Roblox, như cuộn trong một ScrollingFrame, kiểm tra giá trị gameProcessedEvent là sai.Sự kiện này có thể được sử dụng cùng với UserInputService.InputBegan và UserInputService.InputEnded để theo dõi khi nào người dùng bắt đầu nhập, thay đổi và kết thúc.
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Tham Số
Một ví ví dụ / trường hợp, chứa thông tin về nhập của người dùng.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
The following example demonstrates one of many usage examples of handling user input from InputChanged depending on its type.
-- 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
Sự kiện InputEnded bắt lửa khi một người dùng ngừng tương tác thông qua thiết bị Giao diện Con người - Máy tính (nhấn nút chuột xuống, chạm bắt đầu, nút bàn phím xuống, v.v.).Nó hữu ích khi theo dõi khi người dùng phát hành phím bàn phím, nút chuột, đầu vào cảm ứng, v.v.
Sự kiện này có thể được sử dụng cùng với UserInputService.InputBegan và UserInputService.InputChanged để theo dõi khi nào bắt đầu nhập, thay đổi và kết thúc của người dùng.
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Tham Số
Một ví ví dụ / trường hợp, chứa thông tin về nhập của người dùng.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
The following example demonstrates one of many usage examples of handling user input from InputEnded depending on its type.
-- 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
Sự kiện JumpRequest UserInputService bắt lửa khi có yêu cầu nhảy từ khách hàng, ví dụ khi khách hàng nhấn phím cách hoặc nút nhảy trên di động.
Sự kiện này bắt lửa bất cứ khi nào người dùng cố gắng thực hiện nhảy Player.Character của họ.Hành vi mặc định đáp ứng yêu cầu nhảy bằng cách đặt thuộc tính Humanoid.Jump của người chơi thành true, làm cho nhân vật của người chơi nhảy.
Sự kiện có thể được sử dụng để theo dõi mỗi khi một người chơi muốn nhảy.Thay vì sử dụng nó để làm cho một người chơi nhảy, nó nên được sử dụng để thay đổi hành vi nhảy mặc định - như vô hiệu hóa nhảy.
Ví dụ, mã dưới đây in ra "Nhảy" mỗi khi người chơi gửi yêu cầu nhảy.
local UserInputService = game:GetService("UserInputService")
function onJumpRequest()
print("Jump!")
end
UserInputService.JumpRequest:Connect(onJumpRequest)
Vì sự kiện này bắt lửa nhiều lần cho một yêu cầu nhảy duy nhất, sử dụng một giảm thời gian trễ là được đề xuất.
Nếu bạn muốn kết nối các phím hoặc nút với các hành động khác, hãy xem xét sử dụng sự kiện như UserInputService:GetKeysPressed() và UserInputService.InputBegan hoặc ContextActionService.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Mẫu mã
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.
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
Sự kiện UserInputService.LastInputTypeChanged xảy ra bất cứ khi nào khách hàng thay đổi cách tương tác của họ thông qua thiết bị Giao diện Con người - Máy tính.(i.e.từ MouseMovement đến MouseWheel hoặc từ Thumbstick1 đến Thumbstick2).
Để lấy giá trị của loại nhập cuối cùng, bất kể nó có thay đổi hay không, bạn có thể sử dụng chức năng UserInputService:GetLastInputType().
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Tham Số
A Enum.UserInputType được chỉ ra đánh máynhập cuối cùng.
Mẫu mã
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.
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
Hành động chỉ mục bắt lửa khi người dùng thực hiện một hành động chỉ mục cụ thể. Cụ thể, cuộn bánh xe chuột.
Tham Số
TextBoxFocusReleased
Sự kiện TextBoxFocusReleased bắt lửa khi một khách hàng mất tập trung vào một TextBox , thường là khi một khách hàng dừng nhập văn bản bằng cách nhấn enter hoặc nhấp/chạm vào nơi khác trên màn hình.
Ví dụ, mã dưới đây in tên của TextBox mất tập trung khi sự kiện bắt lửa.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocusReleased(textbox)
print(textbox.Name)
end
UserInputService.TextBoxFocusReleased:Connect(TextBoxFocusReleased)
Nó có thể được sử dụng cùng với UserInputService.TextBoxFocused để theo dõi khi một TextBox kiếm được và mất tập trung.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm
Tham Số
TextBoxFocused
Sự kiện này bắt lửa khi có sự tập trung vào một TextBox , thường là khi khách hàng nhấp vào một hộp văn bản để bắt đầu nhập vào văn bản.Điều này cũng bắn nếu tập trung vào hộp văn bản được tập trung bằng cách sử dụng TextBox:CaptureFocus() .
Ví dụ, mã dưới đây in tên của TextBox tập trung khi sự kiện bắt lửa.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocused(textbox)
print(textbox.Name)
end)
UserInputService.TextBoxFocused:Connect(TextBoxFocused)
Nó có thể được sử dụng cùng với UserInputService.FocusReleased để theo dõi khi một hộp văn bản nhận được và mất tập trung.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm
Tham Số
TouchDrag
Tham Số
TouchEnded
Sự kiện TouchEnded bắt lửa khi một người dùng thả ngón tay khỏi màn hình của một thiết bị TouchEnabled, kết thúc đầu vào chạm với thiết bị.
Sự kiện này có thể được sử dụng để xác định khi nào người dùng ngừng chạm vào màn hình của thiết bị của họ.Nó có thể được ghép cặp với UserInputService.TouchStarted để xác định khi nào một người dùng bắt đầu và ngừng chạm vào màn hình.
Ví dụ, mã dưới đây in vị trí màn hình mà người dùng dừng chạm vào màn hình.
local UserInputService = game:GetService("UserInputService")
function TouchEnded(touch, gameProcessedEvent)
print("Touch ended at " .. tostring(touch.Position))
end
UserInputService.TouchEnded:Connect(TouchEnded)
Đối tượng nhập chạm là cùng một đối tượng nhập suốt cuộc sống của chạm.Vì vậy, so sánh InputObjects khi chúng là đối tượng chạm là hợp lệ để xác định xem có phải là cùng một ngón tay hay không.
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Một ví ví dụ / trường hợp, chứa thông tin về nhập của người dùng.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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.
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
Bị sa thả khi người dùng giữ ít nhất một ngón tay trong một thời gian ngắn trên cùng một vị trí màn hình của một thiết bị Bật chạm.
Sự kiện này có thể được sử dụng để xác định khi nào người dùng giữ ngón tay của họ xuống trên một đối tượng trong trò chơi GuiObject hoặc thành phần.
Ví dụ dưới đây in ra state của lần nhấn dài khi người dùng giữ ít nhất một ngón tay trong một thời gian ngắn trên cùng một vị trí màn hình.Các trạng thái có thể bao gồm: Bắt đầu , Thay đổi , Kết thúc , Hủy bỏ , và Không có .
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)
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Nó có thể được kết hợp với UserInputService.TouchStarted và UserInputService.TouchEnded để xác định khi nào một người dùng bắt đầu và ngừng chạm vào màn hình.
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Một mảng của Vector2 đối tượng, chỉ ra vị trí của các ngón tay liên quan đến cử chỉ.
The Enum.UserInputState của cử chỉ.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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.
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
Bắt lửa khi người dùng di chuyển ngón tay trên thiết bị TouchEnabled như một máy tính bảng hoặc điện thoại thông minh.
Sự kiện này hữu ích để theo dõi xem người dùng có di chuyển ngón tay trên màn hình hay không, cũng như nơi người dùng di chuyển ngón tay.
Mã bên dưới hiển thị cú chạm di chuyển từ vị trí trước đến vị trí mới trên thiết bị TouchEnabled .Lưu ý rằng InputObject.Position trên tham số truyền touch là một Vector3 , nhưng chỉ bao gồm X và Y điểm; Z luôn là 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)
Kết hợp sự kiện này với UserInputService.TouchStarted và UserInputService.TouchEnded để xác định khi nào một người bắt đầu chạm vào màn hình, cách ngón tay của họ di chuyển khi chạm vào nó, và khi họ dừng chạm vào màn hình.
Để kiểm tra xem thiết bị của người dùng có hỗ trợ chạm và sự kiện chạm sẽ bắt lửa hay không, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Một ví ví dụ / trường hợp, chứa thông tin về nhập của người dùng.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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.
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
Sự kiện TouchPan bắt lửa khi người dùng kéo ít nhất một ngón tay trên một thiết bị TouchEnabled.
Sự kiện này có thể được sử dụng để xác định khi nào người dùng di chuyển ngón tay trên màn hình của một thiết bị Bật chạm - chẳng hạn như để xoay Camera trong một kịch bản máy ảnh tùy chỉnh.
Phần mã dưới đây in ra "Tốc độ di chuột" theo sau bởi tốc độ chạm của người dùng khi người dùng kéo ngón tay lên màn hình.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
print("Speed of touch drag: " .. tostring(velocity))
end)
Hãy xem thử chức năng hữu ích khác UserInputService ở đây UserInputService.TouchRotate .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Một mảng của Vector2 đối tượng, chỉ ra vị trí của các phím (ví dụ: ngón tay) liên quan đến cử chỉ.
Kích thước của cử chỉ chảo từ đầu đến cuối (bằng pixel).
Tốc độ của cử chỉ chảo (bằng pixel) mỗi giây.
The Enum.UserInputState của cử chỉ.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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:
- Mobile camera events, which rely on touch events
- 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.
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
Bị bắn khi một người dùng đặt và di chuyển hai ngón tay lên màn hình của một thiết bị TouchEnabled .
Ví ví dụ / trường hợp, đoạn mã dưới đây in ra số lần thay đổi phạm vi phóng to của máy ảnh kể từ khi bắt đầu vuốt chạm.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPinch:Connect(function(touchPositions, scale, velocity, state, gameProcessedEvent)
print("Scale difference since beginning of pinch: " .. tostring(scale))
end)
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí.Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Một mảng của Vector2s, chỉ vị trí màn hình, bằng pixel, của các ngón tay liên quan đến cử chỉ gắp.
Mức độ siết từ đầu đến cuối (bằng pixel) chia cho vị trí siết bắt đầu.
Tốc độ của cử chỉ kéo (bằng pixel) mỗi giây.
The Enum.UserInputState của cử chỉ.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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:
- Mobile camera events, which rely on touch events
- 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.
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
Sự kiện TouchRotate bắt lửa khi một người dùng xoay hai ngón tay trên một thiết bị TouchEnabled .
Ví dụ, mã sau in ra số lượng camera đã xoay bao nhiêu kể từ khi bắt đầu xoay chạm.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchRotate:Connect(function(touchPositions, rotation, velocity, state, gameProcessedEvent)
print("Camera has rotated " .. tostring(rotation) .. " degrees!")
end)
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Các kịch bản lõi kiểm soát máy ảnh của người dùng trên thiết bị di động sử dụng mã hoạt động tương tự như sự kiện này.Tốt nhất cho sự kiện này là sử dụng nó khi tạo một hệ thống máy ảnh di động để thay thế các kịch bản lõi mặc định.
Xem thêm:
Tham Số
Số độ mà cử chỉ đã xoay kể từ khi bắt đầu cử chỉ.
Sự thay đổi trong quay (theo độ) chia cho thời gian thay đổi (theo giây).
The Enum.UserInputState của cử chỉ.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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:
- Mobile camera events, which rely on touch events
- 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.
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
Sự kiện TouchStarted bắt lửa khi một người dùng đặt ngón tay lên một thiết bị TouchEnabled, bắt đầu nhập chạm với thiết bị.
Sự kiện này có thể được sử dụng để xác định khi người dùng bắt đầu chạm vào màn hình của thiết bị của họ.Nó có thể được ghép cặp với UserInputService.TouchEnded để xác định khi nào một người dùng bắt đầu và ngừng chạm vào màn hình.
Đối tượng nhập chạm là cùng một đối tượng nhập suốt cuộc sống của chạm.Vì vậy, so sánh InputObjects khi chúng là đối tượng chạm là hợp lệ để xác định xem có phải là cùng một ngón tay hay không.
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Một ví ví dụ / trường hợp, chứa thông tin về nhập của người dùng.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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.
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
Sự kiện TouchSwipe bắt lửa khi một người dùng vuốt ngón tay trên một thiết bị TouchEnabled.
Sự kiện này có thể được sử dụng để xác định khi nào người dùng quẹt ngón tay trên màn hình của thiết bị của họ và hướng mà người dùng quẹt.
Để theo dõi chính xác hơn về chuyển động nhập chạm, hãy sử dụng UserInputService.TouchMoved
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Một Enum.SwipeDirection , chỉ ra hướng mà người dùng đã vuốt.
Số lần chạm (ví dụ: ngón tay) tham gia vào cử chỉ.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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.
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
Sự kiện TouchTap bắt lửa khi người dùng chạm/nhấn ngón tay vào màn hình trên một thiết bị TouchEnabled .
Sự kiện này sẽ bắn ra bất kể người dùng có chạm/nhấn vào thế giới trò chơi hay một thành phần GuiObject không.Nếu bạn đang tìm kiếm một sự kiện chỉ bắt lửa khi người dùng chạm/nhấn vào thế giới trò chơi, hãy sử dụng UserInputService.TouchTapInWorld .
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Tham Số
Một mảng của Vector2 đối tượng, chỉ ra vị trí của các ngón tay liên quan đến cử chỉ chạm.
Chỉ ra xem liệu động cơ trò chơi có quan sát nhập này và hành động trên nó hay không.Nói chung, điều này đề cập đến xử lý UI, vì vậy nếu một nút được chạm hoặc nhấp từ đầu vào này, gameProcessedEvent sẽ là true .Điều này cũng đúng với sự kiện nhập kết nối thông qua ContextActionService .
Mẫu mã
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.
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
Sự kiện TouchTapInWorld bắt lửa khi người dùng chạm/nhấn ngón tay vào màn hình trên một thiết bị TouchEnabled .Nó được kích hoạt khi người dùng nhấn vào thế giới trò chơi.
Sự kiện này có thể được sử dụng để xác định khi nào người dùng nhấn vào màn hình và không nhấn vào một thành phần GuiObject .Nếu người dùng nhấn vào một thành phần GUI, UserInputService.TouchTap sẽ bắn thay vì TouchTapInWorld.
Để kiểm tra xem thiết bị của người dùng có bật TouchEnabled hay không, và các sự kiện chạm sẽ bắt lửa, xem UserInputService.TouchEnabled .
Sự kiện này chỉ bắt lửa khi cửa sổ khách hàng Roblox đang ở trong tâm trí. Ví dụ, các đầu vào sẽ không bị thu thập khi cửa sổ được thu nhỏ.
Vì chỉ bắn chỉ địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Xem thêm:
Tham Số
Whether người dùng đã nhấn vào một thành phần GUI.
Mẫu mã
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.
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
Sự kiện WindowFocusReleased xảy ra khi cửa sổ của khách hàng Roblox mất tập trung - thường là khi khách hàng Roblox bị thu nhỏ bởi người dùng.
Ví dụ, mã bên dưới in "Tập trung cửa sổ được phát hành" bất cứ khi nào khách hàng Roblox mất tập trung.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocusReleased:Connect(function()
print("Window focus released")
end)
Sự kiện này có thể được sử dụng cùng với UserInputService.WindowFocused để theo dõi xem liệu khách hàng Roblox có đang tập trung chủ động vào màn hình của người dùng hay không.
Vì nó chỉ bắn lokal, nó chỉ có thể được sử dụng trong một LocalScript .
Mẫu mã
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)
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)
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
Sự kiện WindowFocused xảy ra khi cửa sổ của khách hàng Roblox nhận được sự tập trung - thường là khi khách hàng Roblox được tối đa hóa/mở một cách chủ động trên màn hình của người dùng.
Ví dụ, mã dưới đây in "Cửa sổ tập trung" mỗi khi khách hàng Roblox nhận được sự tập trung.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocused:Connect(function()
print("Window focused")
end)
Sự kiện này có thể được sử dụng cùng với UserInputService.WindowFocusReleased để theo dõi xem liệu khách hàng Roblox có đang tập trung chủ động vào màn hình của người dùng hay không.
Vì sự kiện này chỉ bắt lửa địa phương, nó chỉ có thể được sử dụng trong một LocalScript .
Mẫu mã
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)
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)
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)