UserInputService
*Konten ini diterjemahkan menggunakan AI (Beta) dan mungkin mengandung kesalahan. Untuk melihat halaman ini dalam bahasa Inggris, klik di sini.
UserInputService adalah layanan yang digunakan untuk mendeteksi dan menangkap berbagai jenis input yang tersedia di perangkat pengguna.
Tujuan utama dari layanan ini adalah untuk memungkinkan pengalaman untuk bekerja sama dengan banyak bentuk input yang tersedia, seperti gamepad, layar sentuh, dan keyboard.Ini memungkinkan LocalScript untuk melakukan tindakan berbeda tergantung pada perangkat dan, pada gilirannya, memberikan pengalaman terbaik bagi pengguna akhir.
Beberapa penggunaan layanan ini termasuk mendeteksi input pengguna saat mereka berinteraksi dengan GUI, alat, dan instans game lainnya.Untuk mendeteksi input pengguna, layanan harus mencari peristiwa layanan.Sebagai contoh, layanan dapat mendeteksi peristiwa seperti ketika pengguna menyentuh layar perangkat seluler menggunakan UserInputService.TouchStarted , atau menghubungkan gamepad seperti kontroler Xbox ke perangkat mereka menggunakan UserInputService.GamepadConnected .
Karena layanan ini hanya sisi klien, itu hanya akan berfungsi saat digunakan dalam LocalScript atau ModuleScript yang diperlukan oleh LocalScript .Karena UserInputService hanya sisi klien, pengguna di dalam game hanya dapat mendeteksi input mereka sendiri - dan bukan input orang lain.
Lihat juga ContextActionService , sebuah layanan yang memungkinkan Anda untuk mengikat fungsi ke banyak input pengguna.
Contoh Kode
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)
Rangkuman
Properti
Menggambarkan apakah perangkat pengguna memiliki accelerometer.
Menggambarkan apakah perangkat yang digunakan oleh pengguna memiliki gamepad yang tersedia.
Menggambarkan apakah perangkat pengguna memiliki gyroskop.
Menggambarkan apakah perangkat pengguna memiliki keyboard yang tersedia.
Menentukan apakah mouse pengguna dapat dipindahkan bebas atau dikunci.
Skala output delta (perubahan) dari pengguna Mouse .
Menggambarkan apakah perangkat pengguna memiliki mouse yang tersedia.
ID konten dari gambar yang digunakan sebagai ikon mouse pengguna.
Menentukan apakah ikon Mouse terlihat.
Menentukan posisi keyboard di layar.
Menentukan ukuran keyboard di layar.
Menggambarkan apakah keyboard di layar saat ini terlihat di layar pengguna.
Menggambarkan apakah perangkat saat ini pengguna memiliki layar sentuh yang tersedia.
Menunjukkan apakah pengguna menggunakan headset realitas virtual.
Metode
Kembalikan apakah gamepad yang diberikan Enum.UserInputType mendukung tombol yang sesuai dengan tombol yang diberikan Enum.KeyCode.
Kembalikan array dari Enum.UserInputType gamepad yang saat ini terhubung.
Kembalikan InputObject yang menggambarkan akselerasi saat ini perangkat.
Kembalikan InputObject yang menjelaskan vektor gravitasi saat ini perangkat.
Kembalikan InputObject dan CFrame , yang menggambarkan vektor rotasi saat ini perangkat.
Kembalikan saat ini TextBox klien saat ini difokuskan pada.
Kembalikan apakah gamepad dengan Enum.UserInputType ''gamepadNum'' yang diberikan terhubung.
Kembalikan array dari InputObjects untuk semua input yang tersedia di gamepad yang diberikan, yang mewakili negara input terakhir setiap input.
Kembalikan gambar untuk permintaan Enum.KeyCode yang diminta.
Kembalikan array dari InputObjects yang terkait dengan keys yang saat ini ditekan.
Kembalikan Enum.UserInputType yang terkait dengan input terbaru pengguna.
Kembalikan array dari InputObjects yang sesuai dengan tombol mouse yang saat ini ditekan.
Kembalikan perubahan, dalam piksel, dari posisi pemain Mouse di frame terakhir yang dirender. Hanya berfungsi jika mouse dikunci.
Kembalikan lokasi layar saat ini dari Mouse pemain terhadap sudut kiri atas layar.
Kembalikan array dari gamepads terhubung dan diaktifkan untuk navigasi GUI dalam urutan prioritas menurun.
Kembalikan string yang mewakili kunci yang harus ditekan pengguna untuk memasukkan Enum.KeyCode tertentu.
Kembalikan array dari KeyCodes yang gamepad yang terkait dengan yang diberikan Enum.UserInputType mendukung.
Menentukan apakah tombol tertentu ditekan pada gamepad tertentu.
Kembalikan apakah yang diberikan key saat ini ditahan.
Kembalikan apakah yang diberikan mouse button saat ini ditahan.
Kembalikan benar jika gamepad yang ditentukan Enum.UserInputType diizinkan untuk mengontrol navigasi GuiObjects .
Mengatur ulang CFrame dari headset VR ke orientasi saat ini dari headset yang dipakai oleh pengguna.
Mengatur apakah atau tidak spesifikasi Gamepad dapat memindahkan navigator GuiObject.
Acara
Dipecat ketika pengguna memindahkan perangkat yang memiliki akselerometer. Digunakan untuk melacak gerakan perangkat dunia nyata dalam gameRoblox.
Ditembak ketika gaya gravitasi berubah pada perangkat yang memiliki akselerometer yang diaktifkan - seperti perangkat seluler.
Ditembak ketika pengguna memutar perangkat yang memiliki gyroskop.
Memicu ketika gamepad terhubung ke klien. Melewati "gamepadNum" dari gamepad yang terhubung.
Memicu ketika gamepad terputus dari klien. Melewati Enum.UserInputType dari gamepad yang terputus.
Ditembak ketika pengguna mulai berinteraksi melalui perangkat Antarmuka Manusia-Komputer - seperti mouse atau gamepad.
Ditembak ketika pengguna mengubah cara mereka berinteraksi melalui perangkat Antarmuka Manusia-Komputer.
Melepaskan api saat pengguna berhenti berinteraksi melalui perangkat Antarmuka Manusia-Komputer.
Memicu kebakaran setiap kali klien membuat permintaan untuk karakter mereka loncat.
Melepaskan api saat Enum.UserInputType klien diubah.
- PointerAction(wheel : number,pan : Vector2,pinch : number,gameProcessedEvent : boolean):RBXScriptSignal
Melepaskan api saat pengguna melakukan tindakan penunjuk khusus (roda, pinch, pan).
Ditembak ketika klien kehilangan fokus pada TextBox.
Ditembak ketika klien fokus pada TextBox.
- TouchDrag(dragDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Ditembak ketika pengguna melepaskan jari mereka dari layar pada perangkat yang diaktifkan sentuh - seperti layar perangkat seluler.
- TouchLongPress(touchPositions : Array,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Ditembak ketika pengguna memegang setidaknya satu jari selama waktu yang singkat di posisi layar yang sama pada perangkat TouchEnabled - seperti layar perangkat seluler.
Melepaskan api saat pengguna menggerakkan jari mereka di perangkat TouchEnabled seperti tablet atau ponsel pintar.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Ditembak ketika pengguna menyeret setidaknya satu jari di perangkat TouchEnabled - seperti layar perangkat seluler.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Ditembak ketika pengguna menggesek jari mereka di perangkat TouchEnabled - seperti layar perangkat seluler.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Melepaskan api saat pengguna memutar dua jari pada perangkat TouchEnabled - seperti layar perangkat seluler.
Ditembak ketika pengguna menempatkan jari mereka di perangkat TouchEnabled - seperti layar iPad atau iPhone Apple atau ponsel Android Google.
- TouchSwipe(swipeDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Api pada perangkat TouchEnabled ketika pengguna menempatkan jari(jari) mereka di layar, melintasi layar, dan mengangkat jari mereka dengan kecepatan gerakan tertentu.
Ditembak ketika pengguna mengetuk jari mereka di perangkat TouchEnabled - seperti layar perangkat seluler.
Melepaskan api saat pengguna mengetuk dunia permainan di perangkat TouchEnabled - seperti layar perangkat seluler.
Melepaskan api saat jendela klien Roblox kehilangan fokus pada layar pengguna.
Melepaskan api saat jendela klien Roblox mendapat fokus pada layar pengguna.
Properti
AccelerometerEnabled
Properti ini menggambarkan apakah perangkat pengguna memiliki accelerometer
Akselerometer adalah komponen yang ditemukan di sebagian besar perangkat seluler yang mengukur akselerasi (perubahan kecepatan).
Sebagai contoh, potongan kode berikut menunjukkan cara memeriksa apakah perangkat pengguna memiliki accelerometer.
local UserInputService = game:GetService("UserInputService")local accelerometerEnabled = UserInputService.AccelerometerEnabledif accelerometerEnabled thenprint("Accelerometer enabled!")elseprint("Accelerometer not enabled!")end
Jika perangkat memiliki akselerometer yang diaktifkan, Anda dapat mendapatkan akselerasi saat ini dengan menggunakan fungsi UserInputService:GetDeviceAcceleration() atau melacak ketika akselerasi perangkat berubah dengan menggunakan peristiwa UserInputService.DeviceAccelerationChanged.
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Contoh Kode
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
Properti ini menjelaskan apakah perangkat yang digunakan oleh pengguna memiliki gamepad yang tersedia.Jika gamepad tersedia, Anda dapat menggunakan UserInputService:GetConnectedGamepads() untuk mengambil daftar gamepad yang terhubung.
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Lihat juga:
Contoh Kode
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
Properti ini menjelaskan apakah perangkat pengguna memiliki gyroskop.
Gyroskop adalah komponen yang ditemukan di sebagian besar perangkat seluler yang mendeteksi orientasi dan kecepatan rotasi.
Jika perangkat pengguna memiliki gyroskop, Anda dapat menggunakannya untuk memasukkannya ke dalam permainan menggunakan fungsi UserInputService:GetDeviceRotation() dan acara UserInputService.DeviceRotationChanged.
local UserInputService = game:GetService("UserInputService")local gyroIsEnabled = UserInputService.GyroscopeEnabledif gyroIsEnabled thenprint("Gyroscope is enabled!")elseprint("Gyroscope is not enabled!")end
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Contoh Kode
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
Properti ini menjelaskan apakah perangkat pengguna memiliki keyboard yang tersedia.Properti ini adalah true ketika perangkat pengguna memiliki keyboard yang tersedia, dan false ketika tidak.
Ini dapat digunakan untuk menentukan apakah pengguna memiliki keyboard yang tersedia - yang bisa menjadi penting jika Anda ingin memeriksa apakah Anda dapat menggunakan UserInputService:IsKeyDown() atau UserInputService:GetKeysPressed() untuk memeriksa input keyboard.
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Contoh Kode
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
Properti ini mengatur bagaimana mouse pengguna berperilaku berdasarkan enum Enum.MouseBehavior. Ini dapat disetel ke tiga nilai:
- Enum.MouseBehavior.Default — Mouse bergerak bebas di sekitar layar pengguna.
- Enum.MouseBehavior.LockCenter — Mouse diblokir dan tidak dapat bergerak dari pusat layar pengguna.
- Enum.MouseBehavior.LockCurrentPosition — Mouse diblokir dan tidak dapat bergerak dari posisi saat ini di layar pengguna saat mengunci.
Nilai properti ini tidak memengaruhi sensitivitas pelacakan gerakan mouse acara.Sebagai contoh, GetMouseDelta kembali posisi layar yang sama Vector2 dalam piksel terlepas dari apakah mouse terkunci atau dapat bergerak bebas di sekitar layar pengguna.Sebagai hasilnya, skrip default seperti yang mengontrol kamera tidak terpengaruh oleh properti ini.
Properti ini dihapus jika GuiButton dengan Modal diaktifkan adalah GuiButton.Visible kecuali tombol mouse kanan pemain turun.
Perhatikan bahwa, jika mouse diblokir, UserInputService.InputChanged masih akan menembak saat pemain memindahkan mouse dan akan melewati Delta yang dimiliki mouse untuk dipindahkan.Selain itu, jika pemain dikeluarkan dari game, mouse akan dibuka dengan kuat.
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Contoh Kode
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
Properti ini menentukan sensitivitas Mouse pengguna.
Sensitivitas menentukan seberapa besar gerakan mouse fisik diterjemahkan menjadi gerakan mouse dalam game.Ini dapat digunakan untuk menyesuaikan bagaimana pelacakan gerakan mouse acara sensitif, seperti GetMouseDelta , untuk gerakan mouse.
Properti ini tidak memengaruhi gerakan ikon mouse.Ini juga tidak memengaruhi pengaturan Sensitivitas Kamera yang ditemukan di tab Pengaturan menu Pengaturan klien, yang juga menyesuaikan sensitivitas pelacakan gerakan mouse acara.
Properti ini memiliki nilai maksimum 10 dan nilai minimum 0.Nilai yang lebih rendah sesuai dengan sensitivitas lebih rendah, dan nilai yang lebih tinggi sesuai dengan sensitivitas lebih tinggi.
Ketika sensitivitas adalah 0, acara yang melacak gerakan mouse masih akan menembak tetapi semua parameter dan properti yang menunjukkan perubahan posisi mouse akan kembali Vector2.new() , atau Vector3.new() dalam kasus InputObject.Delta .Sebagai contoh, GetMouseDelta akan selalu kembali (0, 0).
Contoh Kode
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
Properti ini menjelaskan apakah perangkat pengguna memiliki mouse yang tersedia.Properti ini adalah true ketika perangkat pengguna memiliki mouse yang tersedia, dan false ketika tidak.
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
Penting untuk memeriksa ini sebelum menggunakan fungsi mouse UserInputService seperti UserInputService:GetMouseLocation().
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Lihat juga:
Contoh Kode
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
Properti MouseIcon menentukan gambar yang digunakan sebagai penunjuk.Jika kosong, panah default digunakan.Sementara kursor mengarah ke atas objek UI tertentu seperti ImageButton , TextButton , TextBox , atau ProximityPrompt , gambar ini akan dihapus dan diabaikan sementara.
Untuk menyembunyikan kursor sepenuhnya, lakukan tidak menggunakan gambar transparan. Sebagai gantinya, atur UserInputService.MouseIconEnabled ke false.
Contoh Kode
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
Properti ini menentukan apakah ikon Mouse terlihat ketika true ikon mouse terlihat, ketika false tidak.
Sebagai contoh, potongan kode di bawah ini menyembunyikan ikon mouse.
local UserInputService = game:GetService("UserInputService")UserInputService.MouseIconEnabled = false
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Contoh Kode
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
Properti ini menggambarkan posisi keyboard di layar dalam piksel. Posisi keyboard adalah Vector2.new(0, 0) ketika tidak terlihat.
Sebagai UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript , atau Script dengan RunContext diatur ke Enum.RunContext.Client .
Lihat juga OnScreenKeyboardVisible dan OnScreenKeyboardSize.
Contoh Kode
This example prints the position of the player's on-screen keyboard.
local UserInputService = game:GetService("UserInputService")
print(UserInputService.OnScreenKeyboardPosition)
OnScreenKeyboardSize
Properti ini menggambarkan ukuran keyboard di layar dalam piksel. Ukuran keyboard adalah Vector2.new(0, 0) ketika tidak terlihat.
Sebagai UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript , atau Script dengan RunContext diatur ke Enum.RunContext.Client .
Lihat juga OnScreenKeyboardVisible dan OnScreenKeyboardPosition.
OnScreenKeyboardVisible
Properti ini menjelaskan apakah keyboard di layar saat ini terlihat di layar pengguna.
Sebagai UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript , atau Script dengan RunContext diatur ke Enum.RunContext.Client .
Lihat juga OnScreenKeyboardSize dan OnScreenKeyboardPosition.
TouchEnabled
Properti ini menjelaskan apakah perangkat saat ini pengguna memiliki layar sentuh yang tersedia.
Properti digunakan untuk menentukan apakah perangkat pengguna memiliki layar sentuh, dan karena itu jika peristiwa sentuhan akan ditembak.Jika TouchEnabled benar, Anda dapat menggunakan acara Layanan Input Pengguna seperti UserInputService.TouchStarted dan UserInputService.TouchEnded untuk melacak kapan pengguna mulai dan berhenti menyentuh layar perangkat mereka.
Potongan kode di bawah ini mencetak apakah perangkat pengguna memiliki layar sentuh.
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
Lihat juga:
Contoh Kode
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
Properti ini menjelaskan apakah pengguna menggunakan perangkat virtual reality (VR).
Jika perangkat VR diaktifkan, Anda dapat berinteraksi dengan lokasi dan gerakannya melalui fungsi seperti UserInputService:GetUserCFrame() .Anda juga dapat bereaksi terhadap gerakan perangkat VR menggunakan acara 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
Karena UserInputService hanya sisi klien, properti ini hanya dapat digunakan di LocalScript .
Lihat juga:
Contoh Kode
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
Metode
GamepadSupports
Fungsi ini menghasilkan apakah gamepad yang diberikan Enum.UserInputType mendukung tombol yang sesuai dengan yang diberikan Enum.KeyCode .Fungsi ini digunakan untuk menentukan input gamepad yang valid.
Untuk menentukan gamepad mana yang terhubung, gunakan .
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType dari gamepad.
The Enum.KeyCode dari tombol dalam pertanyaan.
Memberikan nilai
Apakah gamepad yang diberikan mendukung tombol yang sesuai dengan tombol yang diberikan Enum.KeyCode.
Contoh Kode
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
Fungsi ini mengembalikan array dari Enum.UserInputType gamepad yang saat ini terhubung.Jika tidak ada gamepad yang terhubung, array ini akan kosong.Selain itu, hanya mengembalikan objek UserInputType yang merupakan gamepad.Sebagai kejadian, acara ini akan mengembalikan objek Gamepad1 terhubung tetapi bukan objek Keyboard.
Sebagai contoh, bagian kode berikut memperoleh gamepad yang terhubung dan menyimpannya dalam variabel bernama connectedGamepads.
local UserInputService = game:GetService("UserInputService")local connectedGamepads = UserInputService:GetConnectedGamepads()
Untuk memeriksa apakah gamepad khusus terhubung, gunakan UserInputService:GetGamepadConnected() .
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
Memberikan nilai
Sebuah array dari UserInputTypes yang sesuai dengan gamepad yang terhubung ke perangkat pengguna.
Contoh Kode
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
Fungsi GetDeviceAcceleration menentukan akselerasi saat ini dari perangkat pengguna.Ini mengembalikan InputObject yang menggambarkan akselerasi saat ini perangkat.
Untuk agar ini berfungsi, perangkat pengguna harus memiliki accelerometer yang diaktifkan.Untuk memeriksa apakah perangkat pengguna memiliki akselerometer yang diaktifkan, Anda dapat memeriksa properti UserInputService.AccelerometerEnabled.
Jika Anda ingin melacak kapan perubahan akselerasi perangkat pengguna berubah, Anda dapat menggunakan acara UserInputService.DeviceAccelerationChanged.
Karena hanya menembak lokal, hanya dapat digunakan di LocalScript .
Memberikan nilai
Contoh Kode
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
Fungsi ini mengembalikan InputObject yang menjelaskan vektor gravitasi saat ini perangkat.
Vektor gravitasi ditentukan oleh orientasi perangkat relatif terhadap gaya gravitasi dunia nyata.Sebagai kejadian, jika perangkat berdiri sempurna (portrait), vektor gravitasi adalah Vector3.new(0, 0, -9.18) .Jika sisi kiri perangkat menunjuk ke bawah, vektor adalah Vector3.new(9.81, 0, 0).Akhirnya, jika bagian belakang perangkat menunjuk ke bawah, vektor adalah Vector3.new(0, -9.81, 0).
Fungsi ini dapat digunakan untuk mengaktifkan perangkat pengguna untuk mempengaruhi atau mengontrol gravitasi dalam permainan atau memindahkan objek dalam game seperti bola.
Gravitasi hanya dilacak untuk pemain yang menggunakan perangkat dengan kompas yang diaktifkan - seperti perangkat seluler.
Untuk memeriksa apakah perangkat pengguna memiliki kompas yang diaktifkan, periksa nilai UserInputService.GyroscopeEnabled .Jika perangkat memiliki kompas yang diaktifkan, Anda juga dapat menggunakan acara UserInputService.DeviceGravityChanged untuk melacak ketika gaya gravitasi pada perangkat pengguna berubah.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Memberikan nilai
Contoh Kode
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
Fungsi ini mengembalikan InputObject dan CFrame yang menjelaskan vektor rotasi saat ini perangkat.
Ini ditembak dengan InputObject.Properti Posisi dari objek input adalah Enum.InputType.Gyroscope yang melacak rotasi total di setiap sumbu lokal.
Rotasi perangkat hanya dapat dilacak pada perangkat dengan gyroscope.
Karena fungsi ini dinyalakan secara lokal, hanya dapat digunakan di LocalScript .
Memberikan nilai
Sebuah tuple yang berisi dua properti:
- Properti delta menggambarkan jumlah rotasi yang terakhir terjadi
- CFrame adalah rotasi saat ini perangkat relatif terhadap referensi defaultnya.
Contoh Kode
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
Fungsi ini mengembalikan TextBox klien saat ini difokuskan pada.A TextBox dapat dipilih secara manual oleh pengguna, atau pemilihan dapat dipaksa menggunakan fungsi TextBox:CaptureFocus().Jika tidak ada TextBox yang dipilih, fungsi ini akan kembali nil .
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat Juga
Memberikan nilai
GetGamepadConnected
Fungsi ini menyemak apakah gamepad dengan Enum.UserInputType yang diberikan terhubung ke klien.
Ini dapat digunakan untuk memeriksa apakah gamepad khusus, seperti 'Gamepad1' terhubung ke perangkat klien.
Untuk mengambil daftar semua gamepad yang terhubung, gunakan UserInputService:GetConnectedGamepads() .
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType dari gamepad dalam pertanyaan.
Memberikan nilai
Apakah gamepad yang terkait dengan Enum.UserInputType terhubung.
Contoh Kode
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
Fungsi ini mengembalikan array dari InputObjects untuk semua input yang tersedia pada gamepad yang diberikan Enum.UserInputType, yang mewakili negara input terakhir setiap input.
Untuk menemukan UserInputTypes dari gamepad terhubung, gunakan UserInputService:GetConnectedGamepads() .
Karena fungsi ini hanya menembak lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType yang sesuai dengan gamepad dalam pertanyaan.
Memberikan nilai
Sebuah array dari InputObjects yang mewakili status saat ini dari semua input yang tersedia untuk gamepad yang diberikan.
GetImageForKeyCode
Metode ini mengambil Enum.KeyCode yang diminta dan mengembalikan gambar yang terkait untuk perangkat gamepad yang saat ini terhubung (terbatas pada Xbox, PlayStation, dan Windows).Ini berarti bahwa jika kontroler yang terhubung adalah kontroler Xbox One, pengguna melihat aset Xbox.Demikian pula, jika perangkat terhubung adalah kontroler PlayStation, pengguna melihat aset PlayStation.Jika Anda ingin menggunakan aset khusus, lihat GetStringForKeyCode() .
Parameter
The Enum.KeyCode untuk mengambil gambar terkait.
Memberikan nilai
ID aset gambar yang dikembalikan.
Contoh Kode
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
Fungsi ini mengembalikan array dari InputObjects yang terkait dengan tombol yang saat ini ditekan.
배열 ini dapat diulang untuk menentukan kunci mana yang saat ini ditekan, menggunakan nilai InputObject.KeyCode .
Untuk memeriksa apakah kunci tertentu ditekan, gunakan UserInputService:IsKeyDown() .
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Memberikan nilai
Sebuah array dari InputObjects terkait dengan kunci yang saat ini ditekan.
Contoh Kode
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
Fungsi ini men返回 'Enum.UserInputType` yang terkait dengan input terbaru pengguna.
Sebagai contoh, jika input sebelumnya pengguna telah menekan spasi, Enum.UserInputType yang dikembalikan akan menjadi 'Keyboard' .
Peristiwa UserInputService.LastInputTypeChanged dapat digunakan untuk melacak kapan terakhir Enum.UserInputType digunakan oleh perubahan pengguna.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Memberikan nilai
The Enum.UserInputType yang terkait dengan input terbaru pengguna.
Contoh Kode
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
Fungsi ini mengembalikan array dari InputObjects yang sesuai dengan tombol mouse yang saat ini ditekan.
Tombol mouse yang dilacak oleh fungsi ini termasuk:
<td>Deskripsi</td></tr></thead><tr><td>Tombol Mouse1</td><td>Tombol mouse kiri.</td></tr><tr><td>Tombol Mouse2</td><td>Tombol mouse yang tepat.</td></tr><tr><td>Tombol Mouse3</td><td>Tombol tengah mouse.</td></tr>
Nama |
---|
Jika pengguna tidak menekan tombol mouse apa pun saat fungsi dipanggil, itu akan mengembalikan array kosong.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Memberikan nilai
Sebuah array dari InputObjects yang sesuai dengan tombol mouse yang saat ini sedang ditekan.
Contoh Kode
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
Fungsi ini mengembalikan perubahan, dalam piksel, dari posisi pemain Mouse di frame terakhir yang dirender sebagai Vector2.Fungsi ini hanya berfungsi jika mouse telah dikunci menggunakan properti UserInputService.MouseBehavior.Jika mouse belum dikunci, nilai yang dikembalikan Vector2 akan menjadi nol.
Sensitivitas mouse, yang ditentukan dalam pengaturan klien dan UserInputService.MouseDeltaSensitivity , akan mempengaruhi hasil.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Memberikan nilai
Perubahan dalam gerakan mouse.
Contoh Kode
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
Fungsi ini mengembalikan Vector2 yang mewakili lokasi layar saat ini dari Mouse pemain di pixels relatif dengan sudut kiri atas.Ini tidak mempertimbangkan Enum.ScreenInsets ; untuk mendapatkan insersi bagian atas kiri dan bagian bawah kanan, hubungi GuiService:GetGuiInset() .
Jika lokasi pointer mouse berada di luar layar atau perangkat pemain tidak memiliki mouse, nilai yang dikembalikan tidak dapat diidentifikasi.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Memberikan nilai
Contoh Kode
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
Fungsi ini men返回kan array gamepad UserInputTypes yang terhubung dan diaktifkan untuk navigasi GUI.Daftar ini berada dalam urutan prioritas menurun, artinya dapat diulang untuk menentukan gamepad mana yang harus memiliki kontrol navigasi.
Apakah gamepad terhubung adalah gamepad navigasi hanya menentukan gamepad mana (s) yang mengontrol GUI navigasi.Ini tidak mempengaruhi kendalinavigasi.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
- UserInputService:SetNavigationGamepad() , untuk mengaktifkan atau menonaktifkan gamepad untuk navigasi GUI
- UserInputService:IsNavigationGamepad() , untuk memeriksa apakah gamepad diaktifkan untuk navigasi GUI
- UserInputService:GetConnectedGamepads() , untuk mengembalikan semua gamepad yang terhubung terlepas dari kontrol navigasi GUI
Memberikan nilai
Sebuah array dari UserInputTypes yang dapat digunakan untuk navigasi GUI, dalam urutan prioritas menurun.
GetStringForKeyCode
Dapatkan String untuk Kode Kunci kembali string yang mewakili kunci yang harus ditekan pengguna untuk memasukkan kode tertentu Enum.KeyCode , dengan mempertimbangkan tata letak keyboard mereka.Untuk kode kunci yang memerlukan beberapa modifikator untuk dipegang, fungsi ini mengembalikan kunci yang harus ditekan selain modifikator.Lihat contoh di bawah ini untuk penjelasan selanjutnya.
Saat menggunakan Roblox dengan layout keyboard non-QWERTY, kode kunci dikonversi ke posisi QWERTY yang setara.Sebagai contoh, menekan A pada keyboard AZERTY menghasilkan Enum.KeyCode.Q .Pemetaan ini dapat menyebabkan informasi yang tidak cocok pada elemen UI pengalaman.Sebagai contoh, "Tekan M untuk membuka peta" tidak akurat di keyboard AZERTY; perlu "Tekan ? untuk membuka peta" yang berada di posisi yang sama dengan M di QWERTY.Fungsi ini memecahkan masalah ini dengan memberikan kunci aktual yang harus ditekan saat menggunakan layout keyboard non-QWERTY.
local UserInputService = game:GetService("UserInputService")local textLabel = script.Parentlocal mapKey = Enum.KeyCode.MtextLabel.Text = "Press " .. UserInputService:GetStringForKeyCode(mapKey) .. " to open the map"
Contoh di Keyboard QWERTY
<th>Nilai Kembali</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.Q</code></td><td><code>Q</code></td></tr><tr><td><code>Enum.KeyCode.W</code></td><td><code>W</code></td></tr><tr><td><code>Enum.KeyCode.Equals</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.At</code></td><td><code>2</code> karena <code>@</code> ditulis dengan <kbd>Shift</kbd><kbd>2</kbd></td></tr></tbody>
Kode Kunci |
---|
Contoh di Keyboard AZERTY
<th>Nilai Kembali</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.Q</code></td><td><code>A</code></td></tr><tr><td><code>Enum.KeyCode.W</code></td><td><code>Z</code></td></tr><tr><td><code>Enum.KeyCode.Equals</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.At</code></td><td><code>É</code></td></tr></tbody>
Kode Kunci |
---|
Penggunaan Gamepad
mengembalikan peta string untuk gamepad terbaru yang paling terhubung.Jika kontroler terhubung tidak didukung, fungsi mengembalikan konversi string default untuk kode kunci yang diminta.
Contoh berikut menunjukkan bagaimana Anda dapat mengidentifikasi aset khusus untuk 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
Peta Gamepad
Kode tombol pad arah tidak memiliki perbedaan berdasarkan perangkat.Enum.KeyCode.ButtonSelect memiliki perilaku sedikit berbeda di beberapa kasus.Gunakan kedua peta PlayStation untuk memastikan pengguna melihat tombol yang benar.
<th>Nilai Pengembalian PlayStation</th><th>Nilai Kembali Xbox</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonA</code></td><td><code>TombolSalib</code></td><td><code>TombolA</code></td></tr><tr><td><code>Enum.KeyCode.ButtonB</code></td><td><code>Lingkaran Tombol</code></td><td><code>TombolB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonX</code></td><td><code>Tombol Kotak</code></td><td><code>TombolX</code></td></tr><tr><td><code>Enum.KeyCode.ButtonY</code></td><td><code>Triangle Tombol</code></td><td><code>TombolY</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><code>TombolL1</code></td><td><code>TombolLB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL2</code></td><td><code>TombolL2</code></td><td><code>TombolLT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL3</code></td><td><code>TombolL3</code></td><td><code>TombolLS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><code>TombolR1</code></td><td><code>TombolRB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR2</code></td><td><code>TombolR2</code></td><td><code>TombolRT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><code>TombolR3</code></td><td><code>TombolRS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonStart</code></td><td><code>Pengaturan Tombol</code></td><td><code>Tombol Mulai</code></td></tr><tr><td><code>Enum.KeyCode.ButtonSelect</code></td><td><code>TombolTouchpad</code> dan <code>TombolBagikan</code></td><td><code>TombolPilih</code></td></tr></tbody>
Kode Kunci |
---|
Gambar Sistem untuk KeyCodes
Saat menggunakan Enum.KeyCode yang mungkin lebih baik diwakili sebagai gambar, seperti untuk ImageLabel di antarmuka pengguna, Anda dapat menggunakan ikon warisan berikut.Namun, disarankan agar Anda menggunakan GetImageForKeyCode() sebagai metode yang lebih modern dan berbasis cloud untuk mengambil ikon kontroler Xbox dan PlayStation.
<th>Gambaran</th><th>ID Aset</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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/xboxView.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonStart</code></td><td><img src="../../../assets/scripting/controls/xboxmenu.png" width="24"></img></td><td><code>rbxasset://textures/ui/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/xboxRS.png</code></td></tr><tr><td><code>Kumparan Kunci.Code.Thumbstick1</code></td><td><img src="../../../assets/scripting/controls/xboxLSDirectional.png" width="24"></img></td><td><code>rbxasset://textures/ui/Kontrol/xboxLSDirectional.png</code></td></tr><tr><td><code>Kumparan Kunci.Code.Thumbstick2</code></td><td><img src="../../../assets/scripting/controls/xboxRSDirectional.png" width="24"></img></td><td><code>rbxasset://textures/ui/Kontrol/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/Kontrol/backspace.png</code></td></tr><tr><td><code>Kumparan Kode Kunci.Kembali</code></td><td><img src="../../../assets/scripting/controls/return.png" width="24"></img></td><td><code>rbxasset://textures/ui/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/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/Kontrol/koma.png</code></td></tr><tr><td><code>Enum.KeyCode.Kutipan Balik</code></td><td><img src="../../../assets/scripting/controls/graveaccent.png" width="24"></img></td><td><code>rbxasset://textures/ui/Kontrol/graveaccent.png</code></td></tr><tr><td><code>Kumulasi.KeyCode.Period</code></td><td><img src="../../../assets/scripting/controls/period.png" width="24"></img></td><td><code>rbxasset://textures/ui/Kontrol/periode.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/Kontrol/spacebar.png</code></td></tr></tbody>
Kode Kunci |
---|
Parameter
Memberikan nilai
GetSupportedGamepadKeyCodes
Fungsi ini mengembalikan array dari KeyCodes yang gamepad yang terkait dengan Enum.UserInputType yang didukung.
Fungsi ini dapat digunakan untuk menentukan KeyCodes mana yang didukung dan tidak didukung oleh gamepad yang terhubung.Untuk menentukan apakah KeyCode tertentu didukung, gunakan UserInputService:GamepadSupports() .
Jika dipanggil pada gamepad yang tidak ada atau tidak terhubung, fungsi ini akan mengembalikan array kosong.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType dari gamepad.
Memberikan nilai
Contoh Kode
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
Fungsi ini memeriksa apakah tombol tertentu ditekan pada gamepad tertentu.Ini mengembalikan true jika gamepad memiliki tekanan button yang ditentukan, jika tidak maka dikembalikan false.
Jenis Input Pengguna yang Valid
Gamepad yang ditentukan harus menjadi salah satu nilai URI berikut ini:
<tr><td>Enum.UserInputType.Gamepad1-8</td></tr>
Nama |
---|
Kode Kunci Valid
Tombol yang ditentukan harus menjadi salah satu nilai KeyCodes enum berikut:
<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.ButtonStart</td></tr><tr><td>Enum.KeyCode.ButtonSelect</td></tr><tr><td>Enum.KeyCode.DPadLeft</td></tr><tr><td>Enum.KeyCode.DPadRight</td></tr><tr><td>Enum.KeyCode.DPadUp</td></tr><tr><td>Enum.KeyCode.DPadBawah</td></tr>
Nama |
---|
Ini dapat digunakan untuk memeriksa apakah tombol tertentu, seperti A, ditahan. Misalnya:
local UserInputService = game:GetService("UserInputService")local button = Enum.KeyCode.ButtonAlocal gamepad = Enum.UserInputType.Gamepad1local isButtonHeld = UserInputService:IsGamepadButtonDown(gamepad, button)
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
- UserInputService:IsKeyDown() - Metode serupa dengan penggunaan yang berbeda: Untuk memeriksa apakah suatu key di keyboard ditekan.
Parameter
The Enum.UserInputType dari gamepad yang diberikan.
The Enum.KeyCode dari tombol yang ditentukan.
Memberikan nilai
Apakah tombol gamepad yang ditentukan pada gamepad yang diberikan ditekan atau tidak.
Contoh Kode
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
Fungsi ini men返回 apakah pengguna menahan tombol yang terkait dengan kunci yang diberikan Enum.KeyCode.Ini mengembalikan true jika kunci yang ditentukan ditekan atau false jika tidak ditekan.
Ini dapat digunakan untuk memeriksa apakah unittertentu, seperti bilah spasi, ditekan. Misalnya:
local UserInputService = game:GetService("UserInputService")local spaceHeld = UserInputService:IsKeyDown(Enum.KeyCode.Space)
Untuk memulihkan daftar semua tombol yang ditekan oleh pengguna, gunakan fungsi UserInputService:GetKeysPressed().
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
- Enum.UserInputType.IsGamepadButtonDown - Peristiwa serupa dengan penggunaan yang berbeda: Untuk memeriksa apakah suatu button pada gamepad ditekan.
Parameter
The Enum.KeyCode dari unit.
Memberikan nilai
Apakah kunci yang ditentukan ditahan.
Contoh Kode
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
Fungsi ini mengambil tombol mouse Enum.UserInputType dan kembalikan bool yang menunjukkan apakah saat ini ditekan.
Tombol mouse yang diperiksa tergantung pada nilai Enum.UserInputType yang dikirim ke fungsi sebagai argumen. Misalnya:
local UserInputService = game:GetService("UserInputService")local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript."
Parameter
The Enum.UserInputType dari tombol mouse.
Memberikan nilai
Apakah tombol mouse yang diberikan saat ini ditahan.
Contoh Kode
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
Fungsi ini mengembalikan jika gamepad yang ditentukan diizinkan untuk mengontrol Navigasi dan Seleksi .
Jika Anda ingin mengatur gamepad navigasi, Anda dapat menggunakan UserInputService:SetNavigationGamepad() . Anda juga dapat menggunakan UserInputService:GetNavigationGamepads() untuk mendapatkan daftar semua gamepad navigasi.
Sebagai contoh, kode di bawah ini memeriksa apakah gamepad1 adalah sebagai gamepad navigasi:
local UserInputService = game:GetService("UserInputService")if UserInputService:IsNavigationGamepad(UserInputType.Gamepad1) thenprint("Gamepad is a navigation gamepad!")elseprint("Gamepad is not a navigation gamepad!")end
Daftar semua gamepad terhubung, terlepas dari navigasi, dapat diambil menggunakan `UserInput/GetConnectedGamepads.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType dari gamepad yang ditentukan.
Memberikan nilai
Apakah gamepad yang ditentukan adalah gamepad navigasi.
RecenterUserHeadCFrame
Fungsi ini merestabilkan CFrame dari headset VR ke orientasi saat ini dari headset yang dipakai oleh pengguna.Ini berarti bahwa orientasi saat ini headset diatur ke CFrame.new() .
Gunakan fungsi ini untuk memindahkan headset CFrame ke pusat area bermain jika tampaknya berada di offset aneh.
Ini berperilaku identik dengan fungsi VRService , VRService:RecenterUserHeadCFrame() .
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Memberikan nilai
Contoh Kode
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
Fungsi SetNavigationGamepad menetapkan apakah gamepad yang ditentukan Enum.UserInputType dapat memindahkan navigator GUI.Gamepad yang diizinkan untuk memindahkan penjelajah GUI dianggap sebagai gamepad navigasi navigasi.
Jika argumen diaktifkan diberikan sebagai true, Gamepad dapat memindahkan navigator GUI.Jika argumennya adalah false, Gamepad tidak dapat memindahkan navigator GUI.
Jika Anda ingin memeriksa apakah Gamepad yang ditentukan adalah set untuk menjadi gamepad navigasi, Anda dapat menggunakan fungsi UserInputService:IsNavigationGamepad().Anda juga dapat menggunakan UserInputService:GetNavigationGamepads() untuk mengambil daftar semua gamepad navigasi.
Karena UserInputService hanya sisi klien, fungsi ini hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType dari gamepad yang ditentukan.
Apakah gamepad yang ditentukan dapat memindahkan navigator GUI.
Memberikan nilai
Contoh Kode
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)
Acara
DeviceAccelerationChanged
Acara DeviceAccelerationChanged terjadi ketika pengguna memindahkan perangkat yang memiliki akselerometer.
Akselerometer adalah komponen yang ditemukan di sebagian besar perangkat seluler yang mengukur akselerasi (perubahan kecepatan).
Untuk menentukan apakah perangkat pengguna memiliki akselerometer yang diaktifkan, lihat UserInputService.AccelerometerEnabled .
Acara ini dapat digunakan untuk melacak pergerakan perangkat yang memiliki akselerometer.Penggunaan sampel termasuk memindahkan karakter pemain saat perangkat seluler mempercepat.
Selain itu, acara ini dapat digunakan bersama dengan UserInputService:GetDeviceAcceleration() untuk menentukan gerakan saat ini dari perangkat pengguna jika perangkat memiliki accelerometer.
Peristiwa ini hanya terjadi secara lokal - yang berarti hanya pemain yang perangkatnya bergerak yang dapat menggunakan peristiwa tersebut dan hanya akan berfungsi di LocalScript .
Parameter
Sebuah InputObject , dengan UserInputType dari 'Akselerometer' , dan Position yang menunjukkan kekuatan gravitasi pada setiap sumbu lokal.
Contoh Kode
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
Peristiwa UserInputService.DeviceGravityChanged terjadi ketika gravitasi perangkat berubah Vector3 pada perangkat yang memiliki accelerometer.
Vektor gravitasi perangkat mewakili kekuatan gravitasi pada masing-masing sumbu X, Y, dan Z perangkat.Sementara gravitasi tidak pernah berubah, kekuatan yang diberikannya pada setiap sumbu berubah saat perangkat berputar dan berubah orientasi.Nilai gaya yang diterapkan pada setiap sumbu adalah vektor unit berkisar dari -1 hingga 1.
Akselerometer adalah komponen yang ditemukan di sebagian besar perangkat seluler yang mengukur akselerasi (perubahan kecepatan).
Acara ini dapat digunakan untuk menentukan arah dunia nyata dari gaya gravitasi pada perangkat pengguna.Ini bahkan kemudian dapat digunakan untuk menyimulasikan kekuatan gravitasi pada perangkat pengguna dalam permainan, seperti pada objek dalam game (lihat contoh di bawah).
Untuk memeriksa apakah perangkat pengguna memiliki accelerometer yang diaktif, lihat UserInputService.AccelerometerEnabled .Jika perangkat memiliki accelerometer yang diaktifkan, Anda dapat menggunakan fungsi UserInputService:GetDeviceGravity() untuk mendapatkan gaya gravitasi saat ini di perangkat pengguna.
Parameter
Sebuah InputObject , dengan properti InputObject.Position yang menunjukkan kekuatan gravitasi pada setiap sumbu lokal.Posisi ini dapat digunakan sebagai arah untuk menentukan arah gravitasi relatif ke perangkat.
Contoh Kode
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
Acara Perubahan Rotasi Perangkat dimulai ketika pengguna memutar perangkat yang memiliki giroskop.
Gyroskop adalah komponen yang ditemukan di sebagian besar perangkat seluler yang mendeteksi orientasi dan kecepatan rotasi.
Acara berguna saat melacak orientasi perangkat dan bagaimana perubahan saat pengguna memutar perangkat mereka.Untuk menentukan rotasi perangkat saat ini, Anda dapat menggunakan fungsi UserInputService:GetDeviceRotation().
Untuk memeriksa apakah perangkat pengguna memiliki kompas yang diaktifkan, dan bahwa peristiwa ini akan terjadi, lihat UserInputService.GyroscopeEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Parameter
Sebuah InputObject memberikan informasi tentang rotasi perangkat. mewakili rotasi baru nilai posisional dan mewakili perubahan rotasi di nilai posisional .
Contoh Kode
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
Acara GamepadConnected terjadi ketika gamepad terhubung ke klien.
Karena permainan Roblox mendukung beberapa kontroler, acara ini berguna saat dipasangkan dengan acara UserInputService.GamepadDisconnected untuk melacak kontroler/gamepad mana yang aktif.Anda juga dapat menggunakan UserInputService:GetConnectedGamepads() untuk menemukan gamepad yang benar untuk digunakan.
Contoh berikut menunjukkan contoh penggunaan pelacakan saat gamepad terhubung ke klien.
local UserInputService = game:GetService("UserInputService")
local function GamepadConnected(gamepad)
print("Player has plugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadConnected:Connect(GamepadConnected)
Jika Anda ingin melihat perangkat mana yang terhubung, Anda dapat menggunakan fungsi UserInputService:GetConnectedGamepads().
Karena acara ini terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType dari gamepad terhubung.
GamepadDisconnected
Acara GamepadDisconnected terjadi ketika gamepad terputus.
Karena permainan Roblox mendukung beberapa kontroler, acara ini berguna saat dipasangkan dengan acara UserInputService.GamepadConnected untuk melacak kontroler/gamepad mana yang aktif.Anda juga dapat menggunakan UserInputService:GetConnectedGamepads() untuk menemukan gamepad yang benar untuk digunakan.
Contoh berikut menunjukkan contoh penggunaan pelacakan saat gamepad terputus dari klien.
local UserInputService = game:GetService("UserInputService")
local function GamepadDisconnected(gamepad)
print("Player has unplugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadDisconnected:Connect(GamepadDisconnected)
Karena acara ini terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
The Enum.UserInputType dari gamepad terputus.
InputBegan
Acara InputBegan terjadi ketika pengguna mulai berinteraksi melalui perangkat Antarmuka Manusia-Komputer (tombol mouse turun, sentuhan mulai, tombol keyboard turun, dll.).
Ini dapat digunakan untuk melacak awal interaksi pengguna, seperti ketika pengguna pertama kali berinteraksi dengan elemen GUI, gamepad, dll.Ini tidak menangkap gerakan roda mouse.
Acara ini dapat digunakan bersama dengan UserInputService.InputChanged dan UserInputService.InputEnded untuk melacak ketika input pengguna dimulai, berubah, dan berakhir.
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Parameter
Sebuah kejadianInputObject yang berisi informasi tentang input pengguna.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Acara InputChanged terjadi ketika pengguna mengubah cara mereka berinteraksi melalui perangkat Antarmuka Manusia-Komputer (tombol mouse turun, sentuhan mulai, tombol keyboard turun, dll).
Untuk mengabaikan peristiwa yang ditangani secara otomatis oleh Roblox, seperti bergulir di ScrollingFrame , periksa argumen gameProcessedEvent adalah false.Acara ini dapat digunakan bersama dengan UserInputService.InputBegan dan UserInputService.InputEnded untuk melacak kapan input pengguna dimulai, berubah, dan berakhir.
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Parameter
Sebuah kejadianInputObject yang berisi informasi tentang input pengguna.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Acara InputEnded terjadi ketika pengguna berhenti berinteraksi melalui perangkat Antarmuka Manusia-Komputer (tombol mouse turun, sentuhan mulai, tombol keyboard turun, dll).Ini berguna saat melacak ketika pengguna melepaskan tombol keyboard, tombol mouse, input touchscreen, dll.
Acara ini dapat digunakan bersama dengan UserInputService.InputBegan dan UserInputService.InputChanged untuk melacak ketika input pengguna dimulai, berubah, dan berakhir.
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Parameter
Sebuah kejadianInputObject , yang berisi informasi tentang input pengguna.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Peristiwa UserInputService JumpRequest terjadi ketika ada permintaan lompat dari klien, misalnya ketika klien menekan spasi atau tombol lompat di perangkat seluler.
Peristiwa ini terjadi setiap kali pengguna mencoba melakukan loncatPlayer.Character mereka.Perilaku default menanggapi permintaan lompat dengan mengatur properti pemain Humanoid.Jump menjadi benar, yang membuat karakter pemain loncat.
Acara dapat digunakan untuk melacak setiap kali pemain ingin loncat.Alih-alih menggunakannya untuk membuat pemain loncat, ini harus digunakan untuk mengubah perilaku lompatan default - seperti menonaktifkan lompatan.
Sebagai contoh, kode di bawah ini mencetak "Lompat" setiap kali pemain mengirim permintaan lompatan.
local UserInputService = game:GetService("UserInputService")
function onJumpRequest()
print("Jump!")
end
UserInputService.JumpRequest:Connect(onJumpRequest)
Karena acara ini menembak beberapa kali untuk satu permintaan lompatan, menggunakan debounce disarankan.
Jika Anda ingin menghubungkan tombol atau kunci ke tindakan lain, pertimbangkan untuk menggunakan acara seperti UserInputService:GetKeysPressed() dan UserInputService.InputBegan atau ContextActionService.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Contoh Kode
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
Acara UserInputService.LastInputTypeChanged terjadi setiap kali klien mengubah cara mereka berinteraksi melalui perangkat Antarmuka Manusia-Komputer.(i.e.dari MouseMovement ke MouseWheel atau dari Thumbstick1 ke Thumbstick2).
Untuk mendapatkan nilai ketikinput terakhir, terlepas dari apakah itu telah berubah, Anda dapat menggunakan fungsi UserInputService:GetLastInputType().
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Parameter
A Enum.UserInputType menunjukkan ketikinput terakhir.
Contoh Kode
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
Tindakan Penunjuk terbakar saat pengguna melakukan actionpenunjuk khusus. Khususnya, menggulir roda mouse.
Parameter
TextBoxFocusReleased
Peristiwa TextBoxFocusReleased terjadi ketika klien kehilangan fokus pada TextBox , biasanya ketika klien menghentikan masukan teks dengan menekan kembali atau klik/sentuhan di tempat lain di layar.
Sebagai contoh, kode di bawah ini mencetak nama dari TextBox kehilangan fokus saat peristiwa terjadi.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocusReleased(textbox)
print(textbox.Name)
end
UserInputService.TextBoxFocusReleased:Connect(TextBoxFocusReleased)
Ini dapat digunakan bersama dengan UserInputService.TextBoxFocused untuk melacak ketika sebuah TextBox mendapatkan dan kehilangan fokus.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat Juga
Parameter
TextBoxFocused
Peristiwa ini terjadi ketika fokus meningkat pada TextBox, biasanya ketika klien mengklik/mengetuk kotak teks untuk mulai memasukkan teks.Ini juga menembak jika fokus kotak teks difokuskan menggunakan TextBox:CaptureFocus() .
Sebagai contoh, kode di bawah ini mencetak nama TextBox yang difokuskan saat acara terjadi.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocused(textbox)
print(textbox.Name)
end)
UserInputService.TextBoxFocused:Connect(TextBoxFocused)
Ini dapat digunakan bersama dengan UserInputService.FocusReleased untuk melacak ketika kotak teks mendapatkan dan kehilangan fokus.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat Juga
Parameter
TouchDrag
Parameter
TouchEnded
Peristiwa TouchEnded terjadi ketika pengguna melepaskan jari mereka dari layar perangkat TouchEnabled, mengakhiri input sentuhan dengan perangkat.
Acara ini dapat digunakan untuk menentukan kapan pengguna berhenti menyentuh layar perangkat mereka.Ini dapat dipasangkan dengan UserInputService.TouchStarted untuk menentukan kapan pengguna mulai dan berhenti menyentuh layar.
Misalnya, kode di bawah ini mencetak posisi layar di mana pengguna berhenti menyentuh layar.
local UserInputService = game:GetService("UserInputService")
function TouchEnded(touch, gameProcessedEvent)
print("Touch ended at " .. tostring(touch.Position))
end
UserInputService.TouchEnded:Connect(TouchEnded)
Objek input sentuhan adalah objek input yang sama sepanjang masa penggunaan sentuhan.Jadi membandingkan InputObjects ketika mereka adalah objek sentuh adalah valid untuk menentukan apakah itu adalah jari yang sama.
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Sebuah kejadianInputObject yang berisi informasi tentang input pengguna.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Ditembak ketika pengguna memegang setidaknya satu jari selama waktu yang singkat di posisi layar yang sama dari perangkat TouchEnabled.
Acara ini dapat digunakan untuk menentukan kapan pengguna menahan jari mereka di bawah pada elemen atau game dalam GuiObject.
Contoh di bawah ini mencetak state dari tekanan panjang saat pengguna memegang setidaknya satu jari untuk waktu yang singkat di posisi layar yang sama.Status yang mungkin termasuk: Mulai , Perubahan , Akhir , Batalkan , dan Tidak ada .
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)
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Ini dapat dipasangkan dengan UserInputService.TouchStarted dan UserInputService.TouchEnded untuk menentukan kapan pengguna mulai dan berhenti menyentuh layar.
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Sebuah array dari Vector2 objek, yang menunjukkan posisi jari yang terlibat dalam gerakan.
The Enum.UserInputState dari gesture.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Melepaskan api saat pengguna menggerakkan jari mereka di perangkat TouchEnabled seperti tablet atau ponsel pintar.
Acara ini berguna untuk melacak apakah pengguna bergerak jari mereka di layar, serta di mana pengguna bergerak jari mereka.
Kode di bawah ini menunjukkan sentuhan bergerak dari posisi sebelumnya ke posisi baru di perangkat TouchEnabled .Perhatikan bahwa InputObject.Position pada parameter yang dilewati touch adalah Vector3 , tetapi hanya termasuk koordinat X dan Y; Z selalu 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)
Gabungkan acara ini dengan UserInputService.TouchStarted dan UserInputService.TouchEnded untuk menentukan kapan pengguna mulai menyentuh layar, bagaimana jari mereka bergerak saat menyentuhnya, dan kapan mereka berhenti menyentuh layar.
Untuk memeriksa apakah perangkat pengguna mendukung sentuhan dan bahwa peristiwa sentuhan akan ditembakkan, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Sebuah kejadianInputObject yang berisi informasi tentang input pengguna.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Acara TouchPan terjadi ketika pengguna menyeret setidaknya satu jari di perangkat TouchEnabled.
Acara ini dapat digunakan untuk menentukan kapan pengguna menggeser jari mereka di layar perangkat yang diaktifkan sentuh - seperti untuk memutar Camera di skrip kamera khusus.
Potongan kode di bawah ini mencetak "Kecepatan geser sentuhan" diikuti dengan kecepatan sentuhan pengguna saat pengguna menyeret jari mereka di layar.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
print("Speed of touch drag: " .. tostring(velocity))
end)
Lihat fungsi lain berguna UserInputService di sini UserInputService.TouchRotate .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Sebuah array dari Vector2 objek, yang menunjukkan posisi sentuhan (misalnya jari) yang terlibat dalam gerakan.
Ukuran gerakan wajan dari awal sampai akhir (dalam piksel).
Kecepatan gerakan wajan (dalam piksel) per detik.
The Enum.UserInputState dari gesture.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Ditembak ketika pengguna menempatkan dan menggerakkan dua jari di layar perangkat TouchEnabled.
Sebagai kejadian, potongan kode di bawah ini mencetak berapa banyak skala perbesaran kamera telah berubah sejak awal sentuhan pinch.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPinch:Connect(function(touchPositions, scale, velocity, state, gameProcessedEvent)
print("Scale difference since beginning of pinch: " .. tostring(scale))
end)
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus.Sebagai contoh, input tidak akan ditangkap saat jendela dikurangi.Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Sebuah array dari Vector2s , menunjukkan posisi layar, dalam piksel, dari jari yang terlibat dalam gerakan geser.
Besar ukuran pincir dari awal sampai akhir (dalam piksel) dibagi dengan posisi pincir awal.
Kecepatan gerakan pinch (dalam piksel) per detik.
The Enum.UserInputState dari gesture.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Acara Putar Sentuh terjadi ketika pengguna memutar dua jari pada perangkat TouchEnabled .
Sebagai contoh, kode berikut menampilkan berapa banyak kamera telah berputar sejak awal rotasi sentuh.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchRotate:Connect(function(touchPositions, rotation, velocity, state, gameProcessedEvent)
print("Camera has rotated " .. tostring(rotation) .. " degrees!")
end)
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Skrip inti yang mengontrol kamera pengguna di perangkat seluler menggunakan kode yang berfungsi serupa dengan acara ini.Praktik terbaik untuk acara ini adalah menggunakannya saat membuat sistem kamera seluler untuk menggantikan skrip inti default.
Lihat juga:
Parameter
Sebuah array dari Vector2s , menunjukkan posisi jari yang terlibat dalam gerakan.
Jumlah derajat gerakan telah berputar sejak awal gerakan.
Perubahan rotasi (dalam derajat) dibagi dengan durasi perubahan (dalam detik).
The Enum.UserInputState dari gesture.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Acara TouchStarted terjadi ketika pengguna menempatkan jari mereka di perangkat TouchEnabled, memulai input sentuhan dengan perangkat.
Acara ini dapat digunakan untuk menentukan kapan pengguna mulai menyentuh layar perangkat mereka.Ini dapat dipasangkan dengan UserInputService.TouchEnded untuk menentukan kapan pengguna mulai dan berhenti menyentuh layar.
Objek input sentuhan adalah objek input yang sama sepanjang masa penggunaan sentuhan.Jadi membandingkan InputObjects ketika mereka adalah objek sentuh adalah valid untuk menentukan apakah itu adalah jari yang sama.
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Sebuah kejadianInputObject yang berisi informasi tentang input pengguna.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Peristiwa TouchSwipe terjadi ketika pengguna menyentuh jari mereka di perangkat TouchEnabled.
Acara ini dapat digunakan untuk menentukan kapan pengguna menyentuh jari mereka di layar perangkat mereka dan arah yang ditangani pengguna.
Untuk pelacakan sentuhan yang lebih tepat, gunakan UserInputService.TouchMoved
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Sebuah Enum.SwipeDirection , menunjukkan arah yang diseret pengguna.
Jumlah sentuhan (seperti jari) yang terlibat dalam gerakan.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Acara TouchTap terjadi ketika pengguna menyentuh/mengetuk jari mereka di layar pada perangkat TouchEnabled .
Acara ini akan menembak terlepas dari apakah pengguna menyentuh/mengetuk dunia permainan atau elemen GuiObject .Jika Anda mencari acara yang hanya menyala ketika pengguna menyentuh/mengetuk dunia permainan, gunakan UserInputService.TouchTapInWorld .
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Parameter
Sebuah array dari Vector2 objek, yang menunjukkan posisi jari yang terlibat dalam gerakan ketuk.
Menunjukkan apakah mesin permainan secara internal mengamati input ini dan bertindak atasnya.Umumnya ini merujuk pada pemrosesan UI, jadi jika tombol disentuh atau diklik dari input ini, gameProcessedEvent akan menjadi true .Hal ini juga berlaku untuk peristiwa input yang terhubung melalui ContextActionService .
Contoh Kode
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
Acara TouchTapInWorld terjadi ketika pengguna menyentuh/mengetuk jari mereka di layar pada perangkat TouchEnabled.Ini ditembak ketika pengguna mengetuk di dunia permainan.
Acara ini dapat digunakan untuk menentukan kapan pengguna mengetuk layar dan tidak mengetuk elemen GuiObject .Jika pengguna mengetuk elemen GUI, UserInputService.TouchTap akan menembakkan alih-alih TouchTapInWorld.
Untuk memeriksa apakah perangkat pengguna adalah TouchEnabled, dan bahwa peristiwa sentuhan akan ditembak, lihat UserInputService.TouchEnabled .
Acara ini hanya terjadi ketika jendela klien Roblox berfokus. Misalnya, input tidak akan ditangkap saat jendela dikurangi.
Karena hanya menembak lokal, itu hanya dapat digunakan di LocalScript .
Lihat juga:
Parameter
Apakah pengguna mengetuk elemen GUI.
Contoh Kode
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
Peristiwa Fokus Jendela UserInputService dirilis ketika jendela klien Roblox kehilangan fokus - biasanya ketika klien Roblox dikurangi oleh pengguna.
Sebagai contoh, kode di bawah ini mencetak "Fokus jendela dirilis" setiap kali klien Roblox kehilangan fokus.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocusReleased:Connect(function()
print("Window focus released")
end)
Peristiwa ini dapat digunakan bersamaan dengan UserInputService.WindowFocused untuk melacak apakah klien Roblox aktif difokuskan pada layar pengguna.
Karena hanya menembak lokal, hanya dapat digunakan di LocalScript .
Contoh Kode
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
Acara Fokus Jendela pada UserInputService terjadi ketika jendela klien Roblox mendapat fokus - biasanya ketika klien Roblox dimaksimalkan/terbuka aktif di layar pengguna.
Sebagai contoh, kode di bawah ini mencetak "Jendela difokuskan" setiap kali klien Roblox mendapat fokus.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocused:Connect(function()
print("Window focused")
end)
Peristiwa ini dapat digunakan bersamaan dengan UserInputService.WindowFocusReleased untuk melacak apakah klien Roblox aktif difokuskan pada layar pengguna.
Karena acara ini hanya terbakar secara lokal, itu hanya dapat digunakan di LocalScript .
Contoh Kode
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)