UserInputService
*Ta zawartość została przetłumaczona przy użyciu narzędzi AI (w wersji beta) i może zawierać błędy. Aby wyświetlić tę stronę w języku angielskim, kliknij tutaj.
UserInputService jest usługą używaną do wykrywania i przechwytywania różnych rodzajów wejść dostępnych na urządzenieużytkownika.
Głównym celem tej usługi jest umożliwienie współpracy doświadczeń z wieloma formami dostępnego wejścia, takimi jak pady do gier, ekrany dotykowe i klawiatury.Umożliwia LocalScript wykonywanie różnych działań w zależności od urządzenia i, z kolei, zapewnia najlepsze doświadczenia dla użytkownika końcowego.
Niektóre zastosowania tej usługi obejmują wykrywanie wpisów użytkownika podczas interakcji z interfejsami użytkownika, narzędziami i innymi instancjami gry.Aby wykryć wejście użytkownika, usługa musi szukać wydarzenia usługi.Na przykład usługa może wykrywać wydarzenia, takie jak gdy użytkownik dotknie ekranu urządzenia mobilnego za pomocą UserInputService.TouchStarted lub podłączy gamepad, takich jak kontroler Xbox, do swojego urządzenia za pomocą UserInputService.GamepadConnected .
Ponieważ ta usługa jest tylko po stronie klienta, będzie działać tylko wtedy, gdy zostanie użyta w LocalScript lub ModuleScript wymaganym przez LocalScript.Ponieważ Usługa wejścia użytkownika jest tylko po stronie klienta, użytkownicy w grze mogą wykrywać tylko własne wejście - a nie wejście innych.
Zobacz także ContextActionService , usługę, która pozwala wiązać funkcje do wielu wejść użytkownika.
Przykłady kodu
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)
Podsumowanie
Właściwości
Opisuje, czy urządzenie użytkownika ma akcelerometr.
Opisuje, czy urządzenie używane przez użytkownika ma dostępny gamepad.
Opisuje, czy urządzenie użytkownika ma akcelerometr.
Opisuje, czy urządzenie użytkownika ma dostępną klawiaturę.
Określa, czy mysz użytkownika może być swobodnie przesuwana lub jest zamknięta.
Skaluje wyjście delta (zmiana) użytkownika Mouse.
Opisuje, czy urządzenie użytkownika ma dostępną mysz.
ID treści obrazu używanego jako ikona myszy użytkownika.
Określa, czy ikonka Mouse jest widoczna.
Określa pozycję klawiatury na ekranie.
Określa rozmiar klawiatury na ekranie.
Opisuje, czy klawiatura na ekranie jest obecnie widoczna na ekranie użytkownika.
Opisuje, czy aktualne urządzenie użytkownika ma dostępną powierzchnię dotykową.
Wskazuje, czy użytkownik korzysta z goglek wirtualnej rzeczywistości.
Metody
Zwraca, czy podany gamepad Enum.UserInputType wspiera przycisk odpowiadający danemu Enum.KeyCode.
Zwraca tablicę Enum.UserInputType padeł gry obecnie podłączonych.
Zwraca InputObject, który opisuje obecną akcelerację urządzenie.
Zwraca InputObject opisujący obecny wektor grawitacji urządzenie.
Zwraca InputObject i CFrame, opisując aktualny wektor rotacji urządzenie.
Zwraca obecnie TextBox klient jest obecnie skupiony.
Zwraca, czy gamepad z danym Enum.UserInputType "gamepadNum" jest podłączony.
Zwraca array z InputObjects dla wszystkich dostępnych wejść na danym gamepadzie, reprezentujący ostatni stan wejścia każdego wejścia.
Zwraca obraz dla żądanego Enum.KeyCode .
Zwraca tablicę InputObjects powiązanych z keys obecnie naciskanych.
Zwraca Enum.UserInputType powiązane z najnowszym wpisem użytkownika.
Zwraca tablicę InputObjects odpowiadającą przyciskom myszy, które są obecnie przytrzymywane.
Zwraca zmianę, w pikselach, pozycję gracza Mouse w ostatnim renderowanym ramie. Funkcjonuje tylko wtedy, gdy mysz jest zablokowana.
Powraca obecna lokalizacja ekranu gracza względem lewego górnego rogu ekranu. Mouse
Zwraca tablicę gamepads połączonych i włączonych do nawigacji GUI w kolejności malejącego priorytetu.
Zwraca ciąg reprezentujący klucz, który użytkownik powinien nacisnąć, aby wprowadzić dany Enum.KeyCode.
Zwraca tablicę KeyCodes, którą wspiera gamepad powiązany z danym Enum.UserInputType .
Określa, czy dany przycisk jest naciśnięty na określonym gamepadzie.
Zwraca, czy podany key jest obecnie przytrzymywany.
Zwraca, czy podany mouse button jest obecnie przytrzymywany.
Wyświetla prawdę, jeśli określony gamepad Enum.UserInputType pozwala kontrolować nawigację GuiObjects.
Odśrodkowuje CFrame słuchawki VR do obecnego kierunku noszenia słuchawki przez użytkownika.
Ustawia, czy określone Gamepad może przenieść nawigator GuiObject czy nie.
Zdarzenia
Strzelany, gdy użytkownik przenosi urządzenie, które ma akcelerometr. Używany do śledzenia ruchu urządzenia w świecie rzeczywistym w graRoblox.
Wystrzeliwany, gdy siła grawitacji zmienia się na urządzeniu, które ma włączony akcelerometr - na przykład na urządzeniemobilnym.
Wystrzelony, gdy użytkownik obraca urządzenie, które ma akcelerometr.
Wystrzeliwuje, gdy gamepad jest podłączony do klienta. Przekazuje "gamepadNum" z gamepada, który był podłączony.
Wypala się, gdy gamepad jest odłączony od klienta. Przekazuje Enum.UserInputType z gamepada, który został odłączony.
Wystrzeliwany, gdy użytkownik zaczyna interakcję za pomocą urządzenia interfejsu człowiek-komputer, takiego jak mysz lub gamepad.
Wystrzeliwany, gdy użytkownik zmienia sposób interakcji za pomocą urządzenieinterfejsu człowiek-komputer.
Wypala się, gdy użytkownik przestaje interakcjonować za pomocą urządzenieinterfejsu człowiek-komputer.
Wystrzeliwuje za każdym razem, gdy klient wysyła żądanie, aby jego postać skok.
Wystrzeliwuje, gdy zmieniony zostanie Enum.UserInputType klienta.
- PointerAction(wheel : number,pan : Vector2,pinch : number,gameProcessedEvent : boolean):RBXScriptSignal
Wystrzeliwuje, gdy użytkownik wykonuje określoną akcję wskazania (koło, przeciągnięcie, przesuwanie).
Wystrzeliwany, gdy klient traci koncentrację na TextBox.
Wystrzeliwany, gdy klient skupia się na TextBox.
- TouchDrag(dragDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Wystrzeliwany, gdy użytkownik uwalnia palec z ekranu na urządzeniu z włączonym dotykiem - takim jak ekran urządzeniemobilnego.
- TouchLongPress(touchPositions : Array,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Wystrzeliwany, gdy użytkownik trzyma co najmniej jeden palec przez krótki czas na tej samej pozycji ekranu na urządzeniu z włączonym dotykiem - takim jak ekran urządzeniemobilnego.
Wystrzeliwuje, gdy użytkownik przesuwa palec na urządzenieTouchEnabled takim jak tablet lub smartfon.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Wystrzeliwany, gdy użytkownik przeciągnie co najmniej jeden palec na urządzeniu TouchEnabled - takim jak ekran urządzeniemobilnego.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Wystrzeliwany, gdy użytkownik przyciska palce na urządzeniu TouchEnabled - takim jak ekran urządzeniemobilnego.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Wypala się, gdy użytkownik obraca dwa palce na urządzeniu TouchEnabled - takim jak ekran urządzeniemobilnego.
Wystrzeliwany, gdy użytkownik położy palec na urządzeniu z włączonym dotykiem - takim jak ekran Apple iPad lub iPhone lub telefon Google Android.
- TouchSwipe(swipeDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Ogień na urządzeniu TouchEnabled w momencie, gdy użytkownik umieszcza palce na ekranie, przesuwa je po ekranie i odrywa je z pewną prędkością ruchu.
Wystrzeliwany, gdy użytkownik dotknie palcem urządzenia TouchEnabled - takiego jak ekran urządzeniemobilnego.
Wypala się, gdy użytkownik dotknie świata gry na urządzeniu TouchEnabled - takim jak ekran urządzeniemobilnego.
Wystrzeliwuje, gdy okno klienta Roblox traci skupienie na ekranie użytkownika.
Wybucha, gdy okno klienta Roblox zyskuje uwagę na ekranie użytkownika.
Właściwości
AccelerometerEnabled
Właściwość ta opisuje, czy urządzenie użytkownika ma akcelerometr
Akcelerometr to komponent znajdujący się w większości urządzeń mobilnych, który mierzy przyspieszenie (zmianę prędkości).
Na przykład następny kod pokazuje, jak sprawdzić, czy urządzenie użytkownika ma akcelerometr.
local UserInputService = game:GetService("UserInputService")local accelerometerEnabled = UserInputService.AccelerometerEnabledif accelerometerEnabled thenprint("Accelerometer enabled!")elseprint("Accelerometer not enabled!")end
Jeśli urządzenie ma włączony akcelerometr, możesz uzyskać jego obecną akcelerację za pomocą funkcji UserInputService:GetDeviceAcceleration() lub śledzić, gdy akceleracja urządzenia zmienia się za pomocą wydarzenia UserInputService.DeviceAccelerationChanged.
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Przykłady kodu
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
Właściwość ta opisuje, czy urządzenie używane przez użytkownika ma dostępny gamepad.Jeśli dostępne są gamepady, możesz użyć UserInputService:GetConnectedGamepads() aby odzyskać listę połączonych gamepadów.
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Zobacz także:
Przykłady kodu
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
Właściwość ta opisuje, czy urządzenie użytkownika ma akcelerometr.
Gyroskop to komponent znajdujący się w większości urządzeń mobilnych, które wykrywają orientację i prędkość obrotową.
Jeśli urządzenie użytkownika ma akcelerometr, możesz go zintegrować z grą za pomocą funkcji UserInputService:GetDeviceRotation() i wydarzenia UserInputService.DeviceRotationChanged.
local UserInputService = game:GetService("UserInputService")local gyroIsEnabled = UserInputService.GyroscopeEnabledif gyroIsEnabled thenprint("Gyroscope is enabled!")elseprint("Gyroscope is not enabled!")end
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Przykłady kodu
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
Właściwość ta opisuje, czy urządzenie użytkownika ma dostępną klawiaturę.Właściwość ta jest true , gdy urządzenie użytkownika ma dostępną klawiaturę, a false gdy nie ma.
Można go użyć do określenia, czy użytkownik ma dostępną klawiaturę - co może być ważne, jeśli chcesz sprawdzić, czy możesz używać UserInputService:IsKeyDown() lub UserInputService:GetKeysPressed() do sprawdzania wpisu klawiatury.
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Przykłady kodu
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
Właściwość ta określa, jak zachowuje się mysz użytkownika w oparciu o Enum.MouseBehavior enum. Można ją ustawić na trzy wartości:
- Enum.MouseBehavior.Default — Mysz porusza się swobodnie po ekranie użytkownika.
- Enum.MouseBehavior.LockCenter — Mysz jest zablokowana i nie może się poruszać z centrum ekranu użytkownika.
- Enum.MouseBehavior.LockCurrentPosition — Mysz jest zablokowana i nie może się poruszać z jej obecnej pozycji na ekranie użytkownika w momencie blokowania.
Wartość tej właściwości nie wpływa na czułość śledzenia ruchu myszy.Na przykład, GetMouseDelta zwraca tę samą pozycję ekranu Vector2 w pikselach niezależnie od tego, czy mysz jest zablokowana, czy może swobodnie poruszać się po ekranie użytkownika.W wynikdomyślne skrypty, takie jak te kontrolujące kamerę, nie są dotknięte przez tę właściwość.
Właściwość ta jest anulowana, jeśli włączono GuiButton z Modal jeśli prawy przycisk myszy gracza jest w dół, chyba że włączono GuiButton.Visible
Zauważ, że jeśli mysz jest zablokowana, UserInputService.InputChanged nadal wystrzeli, gdy gracz przesunie mysz i przekaże w Delta, którą mysz próbował przesunąć.Ponadto, jeśli gracz zostanie wyrzucony z gry, mysz zostanie siłą odblokowana.
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Przykłady kodu
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
Właściwość ta określa wrażliwość użytkownika Mouse.
Czułość określa zakres, w jakim ruch fizycznej myszy przekłada się na ruch myszy w grze.Można to użyć do dostosowania, w jaki sposób wrażliwe śledzenie ruchu myszy, takie jak GetMouseDelta, ma być dostosowane do ruchu myszy.
Właściwość ta nie wpływa na ruch ikona.Nie wpływa to również na ustawienie czułości kamery znalezione w zakładce Ustawienia menu Ustawienia klienta, które również dostosowuje czułość śledzenia ruchu myszy.
Właściwość ta ma maksymalną wartość 10 i minimalną wartość 0.Wartość niższa odpowiada niższej czułości, a wyższa odpowiada wyższej czułości.
Gdy czułość wynosi 0, wydarzenia śledzące ruch myszy nadal będą wystrzeliwane, ale wszystkie parametry i właściwości wskazujące na zmianę pozycji myszy zwrócą Vector2.new() lub Vector3.new() w przypadku InputObject.Delta.Na przykład GetMouseDelta zawsze zwróci (0, 0).
Przykłady kodu
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
Właściwość ta opisuje, czy urządzenie użytkownika ma dostępną mysz.Właściwość ta jest true, gdy urządzenie użytkownika ma dostępną mysz, a false gdy nie ma.
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
Ważne jest, aby to sprawdzić przed użyciem funkcji myszy UserInputService takich jak UserInputService:GetMouseLocation().
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Zobacz także:
Przykłady kodu
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
Właściwość MouseIcon określa obraz używany jako wskaznik.Jeśli jest pusty, używany jest domyślny strzał.Podczas gdy kurser przewija się nad niektórymi obiektami interfejsu użytkownika, takimi jak ImageButton, TextButton, TextBox lub ProximityPrompt, obraz zostanie zastąpiony i tymczasowo zignorowany.
Aby ukryć całkowicie kursor, nie używaj transparentnego obrazu . Zamiast tego ustaw UserInputService.MouseIconEnabled na fałsz.
Przykłady kodu
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
Właściwość ta określa, czy ikona jest widoczna, gdy ikona myszy jest widoczna, gdy nie jest.
Na przykład kodowy kawałek poniżej ukrywa ikonamyszy.
local UserInputService = game:GetService("UserInputService")UserInputService.MouseIconEnabled = false
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Przykłady kodu
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
Właściwość ta opisuje pozycję klawiatury na ekranie w pikselach. Pozycja klawiatury jest Vector2.new(0, 0) , gdy nie jest widoczna.
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript lub Script z ustawieniem RunContext na Enum.RunContext.Client.
Zobacz także OnScreenKeyboardVisible i OnScreenKeyboardSize.
Przykłady kodu
This example prints the position of the player's on-screen keyboard.
local UserInputService = game:GetService("UserInputService")
print(UserInputService.OnScreenKeyboardPosition)
OnScreenKeyboardSize
Właściwość ta opisuje rozmiar klawiatury na ekranie w pikselach. Rozmiar klawiatury wynosi Vector2.new(0, 0), gdy nie jest widoczna.
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript lub Script z ustawieniem RunContext na Enum.RunContext.Client.
Zobacz także OnScreenKeyboardVisible i OnScreenKeyboardPosition.
OnScreenKeyboardVisible
Właściwość ta opisuje, czy klawiatura na ekranie jest obecnie widoczna na ekranie użytkownika.
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript lub Script z ustawieniem RunContext na Enum.RunContext.Client.
Zobacz także OnScreenKeyboardSize i OnScreenKeyboardPosition.
TouchEnabled
Właściwość ta opisuje, czy aktualne urządzenie użytkownika ma dostępną powierzchnię dotykową.
Właściwość jest używana do określenia, czy urządzenie użytkownika ma ekran dotykowy i dlatego czy zdarzenia dotykowe będą wystrzeliwowane.Jeśli włączone jest dotykanie, możesz używać wydarzeń z usługi UserInputService, takich jak UserInputService.TouchStarted i UserInputService.TouchEnded, aby śledzić, kiedy użytkownik zaczyna i kończy dotykanie ekranu swojego urządzenia.
Kodowy snippet poniżej drukuje, czy urządzenie użytkownika ma ekran dotykowy.
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
Zobacz także:
Przykłady kodu
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
Właściwość ta opisuje, czy użytkownik korzysta z urządzeniewirtualnej rzeczywistości (VR).
Jeśli urządzenie VR jest włączone, możesz wchodzić w interakcję z jego lokalizacją i ruchami za pomocą funkcji takich jak UserInputService:GetUserCFrame().Możesz również reagować na ruch urządzenia VR za pomocą wydarzenia 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
Ponieważ UserInputService jest tylko po stronie klienta, ta właściwość może być używana tylko w LocalScript.
Zobacz także:
Przykłady kodu
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
Metody
GamepadSupports
Funkcja ta zwraca, czy podany gamepad Enum.UserInputType wspiera przycisk odpowiadający danemu Enum.KeyCode.Funkcja ta jest używana do określenia ważnych wejść z pada gry.
Aby określić, które Enum.UserInputType pady gier są podłączone, użyj UserInputService:GetConnectedGamepads().
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType z gamepada.
Przycisk Enum.KeyCode z pytania.
Zwroty
Czy podany gamepad wspiera przycisk odpowiadający danemu Enum.KeyCode.
Przykłady kodu
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
Funkcja ta zwraca tablicę Enum.UserInputType padeł gry obecnie podłączonych.Jeśli żadne gamepady nie są podłączone, ta matryca będzie pusta.Ponadto zwraca tylko obiekty UserInputType, które są gamepadami.Na instancja, to wydarzenie zwróci połączony obiekt Gamepad1, ale nie obiekt klawiatury.
Na przykład następujący kod snippet odzyskuje połączone gamepady i przechowuje je w zmiennej o nazwie connectedGamepads.
local UserInputService = game:GetService("UserInputService")local connectedGamepads = UserInputService:GetConnectedGamepads()
Aby sprawdzić, czy podłączono określoną konsolę, użyj UserInputService:GetGamepadConnected().
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
Zwroty
Zbiór UserInputTypes odpowiadający gamepadom połączonym z urządzeniem użytkownika.
Przykłady kodu
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
Funkcja GetDeviceAcceleration określa obecną akcelerację urządzenieużytkownika.Zwraca InputObject, który opisuje obecną akcelerację urządzenie.
Aby to działało, urządzenie użytkownika musi mieć włączony akcelerometr.Aby sprawdzić, czy urządzenie użytkownika ma akcelerometr włączony, możesz sprawdzić właściwość UserInputService.AccelerometerEnabled.
Jeśli chcesz śledzić zmiany przyspieszenia urządzenieużytkownika zamiast tego, możesz użyć wydarzenia UserInputService.DeviceAccelerationChanged.
Ponieważ strzela tylko lokalnie, może być używany tylko w LocalScript.
Zwroty
Przykłady kodu
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
Funkcja ta zwraca InputObject opisujący obecny wektor grawitacji urządzenie.
Wektor grawitacji jest określany przez orientację urządzenia względem siły grawitacji w świecie rzeczywistym.Na instancja, jeśli urządzenie jest doskonale pionowe (portret), wektor grawitacji wynosi Vector3.new(0, 0, -9.18) .Jeśli lewa strona urządzenia wskazuje w dół, wektor jest Vector3.new(9.81, 0, 0).Wreszcie, jeśli tył urządzenia wskazuje w dół, wektor jest Vector3.new(0, -9.81, 0).
Funkcja ta może być używana do włączenia urządzenia użytkownika, które może wpływać na grawitację w grze lub przemieszczać obiekty w grze, takie jak piłka.
Grawitacja jest śledzona tylko dla graczy używających urządzenia z aktywnym akcelerometrem - takiego jak urządzenie mobilne.
Aby sprawdzić, czy urządzenie użytkownika ma włączony akcelerometr, sprawdź wartość UserInputService.GyroscopeEnabled.Jeśli urządzenie ma włączony akcelerometr, możesz również użyć wydarzenia UserInputService.DeviceGravityChanged, aby śledzić, kiedy siła grawitacji na urządzeniu użytkownika zmienia się.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zwroty
Przykłady kodu
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
Funkcja ta zwraca InputObject i CFrame opisującą aktualny wektor rotacji urządzenie.
Wystrzeliwany jest za pomocą obiektu wejściowego.Właściwość Pozycja obiektu wejściowego jest właściwością Enum.InputType.Gyroscope, która śledzi całkowitą rotację w każdym osi lokalnego urządzenia.
Rotacja urządzenia może być śledzona tylko na urządzeniach z gyroscope.
Ponieważ ta funkcja wystrzeliwuje lokalnie, można jej używać tylko w LocalScript.
Zwroty
Tuple zawierający dwie właściwości:
- Właściwość delta opisuje ilość rotacji, która miała miejsce po raz ostatni
- CFRame to obecna rotacja urządzeniewzględem jego domyślnego ramu odniesienia.
Przykłady kodu
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
Funkcja ta zwraca TextBox klient jest obecnie skoncentrowany na.A TextBox może być wybrane ręcznie przez użytkownika, a wybór może być zmuszony za pomocą funkcji TextBox:CaptureFocus().Jeśli nie zostanie wybrane żadne TextBox, ta funkcja zwróci nil.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także
Zwroty
GetGamepadConnected
Funkcja ta zwraca, czy gamepad z danym Enum.UserInputType jest podłączony do klienta.
Można tego użyć, aby sprawdzić, czy konkretna konsola, tak jak 'Gamepad1', jest podłączona do urządzenieklienta.
Aby odzyskać listę wszystkich połączonych gamepadów, użyj UserInputService:GetConnectedGamepads().
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType z gamepada w kwestii.
Zwroty
Czy gamepad powiązany z Enum.UserInputType jest podłączony.
Przykłady kodu
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
Funkcja ta zwraca tablicę dla wszystkich dostępnych wejść na podanych gamepadzie, reprezentując ostatni stan wejścia każdego wejścia.
Aby znaleźć UserInputTypes połączonych gamepadów, użyj UserInputService:GetConnectedGamepads().
Ponieważ ta funkcja wystrzeliwuje tylko lokalnie, można jej używać tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType odpowiadający gamepadowi w kwestii.
Zwroty
Matryca InputObjects reprezentująca obecny stan wszystkich dostępnych wejść dla danego gamepada.
GetImageForKeyCode
Ta metoda bierze żądaną Enum.KeyCode i zwraca powiązany obraz dla obecnie podłączonego urządzenia gamepad (ograniczony do Xbox, PlayStation i Windows).Oznacza to, że jeśli połączony kontroler jest kontrolerem Xbox One, użytkownik widzi zasoby Xbox.Podobnie, jeśli połączone urządzenie jest kontrolerem PlayStation, użytkownik widzi zasoby PlayStation.Jeśli chcesz korzystać z niestandardowych zasobów, zobacz GetStringForKeyCode().
Parametry
The Enum.KeyCode dla którego należy pobrać powiązany obraz.
Zwroty
ID zwróconego obrazu zasobu.
Przykłady kodu
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
Funkcja ta zwraca tablicę InputObjects powiązanych z klawiszami, które są obecnie naciskane.
Ta tablica może być przetwarzana, aby określić, które klawisze są obecnie naciskane, za pomocą wartości InputObject.KeyCode.
Aby sprawdzić, czy naciśnięto określoną klawisz, użyj UserInputService:IsKeyDown().
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zwroty
Zbiór InputObjects powiązanych z klawiszami obecnie naciśniętych klawisz.
Przykłady kodu
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
Funkcja ta zwraca 'Enum.UserInputType` związany z najnowszym wejściem użytkownika.
Na przykład, jeśli poprzednie wejście użytkownika naciskało spacji, zwrócony byłby Enum.UserInputType'Klawiatura'.
Wydarzenie UserInputService.LastInputTypeChanged może być użyte do śledzenia, kiedy ostatnia Enum.UserInputType zmiana użytkownika została wykorzystana.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zwroty
The Enum.UserInputType związany z najnowszym wpisem użytkownika.
Przykłady kodu
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
Funkcja ta zwraca tablicę InputObjects odpowiadającą przyciskom myszy, które są obecnie naciskane.
Przyciski myszy śledzone przez tę funkcję obejmują:
<td>Opis</td></tr></thead><tr><td>Przycisk myszy1</td><td>Lewe przyciski myszy.</td></tr><tr><td>Przycisk myszy 2</td><td>Prawy przycisk myszy.</td></tr><tr><td>Przycisk myszy 3</td><td>Przycisk środkowej myszy.</td></tr>
Nazwa |
---|
Jeśli użytkownik nie naciska żadnego przycisku myszy, gdy funkcja jest wywoływana, zwróci pustą listę.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zwroty
Zbiór InputObjects odpowiadający przyciskom myszy, które są obecnie przytrzymywane.
Przykłady kodu
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
Funkcja ta zwraca zmianę, w pikselach, pozycji gracza Mouse w ostatnim renderowanym ramie jako Vector2.Funkcja ta działa tylko wtedy, gdy mysz została zablokowana za pomocą właściwości UserInputService.MouseBehavior.Jeśli mysz nie została zablokowana, wartości zwrócone z Vector2 będą wynosić zero.
Czułość myszy, określona w ustawieniach klienta i UserInputService.MouseDeltaSensitivity, wpłynie na wynik.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zwroty
Zmiana ruchu myszy.
Przykłady kodu
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
Funkcja ta zwraca Vector2 reprezentującą obecną lokalizację ekranu gracza Mouse w pikselach względem lewego górnego kąta.Nie uwzględnia to Enum.ScreenInsets ; aby uzyskać wstawki górne lewe i dolne prawe, wezwij GuiService:GetGuiInset() .
Jeśli położenie wskaźnika myszy jest poza ekranem lub urządzenie gracza nie ma myszy, wartość zwrócona zostanie nieokreślona.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zwroty
Przykłady kodu
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
Funkcja ta zwraca tablicę gamepadów UserInputTypes, które są połączone i włączone do nawigacji GUI.Lista ta jest w kolejności malejącego priorytetu, co oznacza, że można ją powtarzać, aby określić, który gamepad powinien mieć kontrolę nawigacji.
Czy połączony gamepad jest gamepadem nawigacyjnym określa tylko, który gamepad kontroluje interfejsy nawigacyjne.Nie wpływa to na elementy sterującenawigacją.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
- UserInputService:SetNavigationGamepad() , aby włączyć lub wyłączyć gamepad do nawigacji GUI
- UserInputService:IsNavigationGamepad() , aby zweryfikować, czy gamepad jest włączony do nawigacji GUI
- UserInputService:GetConnectedGamepads() , aby zwrócić wszystkie pady gry połączone niezależnie od kontroli nawigacyjnej GUI
Zwroty
Zbiór UserInputTypes, który może być używany do nawigacji GUI, w kolejności malejącej priorytetu.
GetStringForKeyCode
GetStringForKeyCode zwraca ciąg reprezentujący klucz, który użytkownik powinien nacisnąć, aby wprowadzić dany Enum.KeyCode, biorąc pod uwagę ich układ klawiatury.Dla kluczowych kodów, które wymagają utrzymania jakiegoś modyfikatora, funkcja ta zwraca klucz, który należy nacisnąć oprócz modyfikatora.Zobacz przykłady poniżej dla dalszego wyjaśnienia.
Podczas używania Roblox z układem klawiatury nie-QWERTY kody kluczy są mapowane do równoważnych pozycji QWERTY.Na przykład naciśnięcie A na klawiaturze AZERTY skutkuje Enum.KeyCode.Q.Ta mapowanie może prowadzić do niezgodnych informacji na temat elementów interfejsu użytkownika doświadczenia.Na przykład "Naciśnij M, aby otworzyć mapę" jest niepoprawne na klawiaturze AZERTY; musiałoby to być "Naciśnij ?, aby otworzyć mapę", co jest w tym samym miejscu, co M na QWERTY.Funkcja ta rozwiązuje ten problem, zapewniając rzeczywisty klucz, który należy nacisnąć podczas korzystania z nie-QWERTY układów klawiatury.
local UserInputService = game:GetService("UserInputService")local textLabel = script.Parentlocal mapKey = Enum.KeyCode.MtextLabel.Text = "Press " .. UserInputService:GetStringForKeyCode(mapKey) .. " to open the map"
Przykłady na klawiaturze QWERTY
<th>Wartość zwrotna</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> ponieważ <code>@</code> jest wpisane z <kbd>Shift</kbd><kbd>2</kbd></td></tr></tbody>
Kod klucza |
---|
Przykłady na klawiaturze AZERTY
<th>Wartość zwrotna</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>
Kod klucza |
---|
Użycie gamepada
GetStringForKeyCode() zwraca mapę strun dla Enum.KeyCode najbardziej ostatnio podłączonego gamepada.Jeśli połączony kontroler nie jest wspierany, funkcja zwraca domyślną konwersję strun dla żądanego kodu klucza.
Poniższy przykład pokazuje, jak można mapować niestandardowe zasoby dla 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
Mapowanie klawiatury gry
Kody klawiszy padu kierunkowego nie różnią się w zależności od urządzenie.Enum.KeyCode.ButtonSelect ma nieco inne zachowanie w niektórych przypadkach.Użyj obu map PlayStation, aby użytkownicy widzieli poprawne przyciski.
<th>Wartość zwrotu PlayStation</th><th>Wartość zwrotu Xbox</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonA</code></td><td><code>PrzyciskCross</code></td><td><code>PrzyciskA</code></td></tr><tr><td><code>Enum.KeyCode.ButtonB</code></td><td><code>Koło przycisków</code></td><td><code>PrzyciskB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonX</code></td><td><code>Przycisk kwadratowy</code></td><td><code>PrzyciskX</code></td></tr><tr><td><code>Enum.KeyCode.ButtonY</code></td><td><code>Przycisk Trójkąt</code></td><td><code>PrzyciskY</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><code>Przycisk L1</code></td><td><code>PrzyciskLB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL2</code></td><td><code>Przycisk L2</code></td><td><code>PrzyciskLT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL3</code></td><td><code>Przycisk L3</code></td><td><code>PrzyciskiLS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><code>Przycisk R1</code></td><td><code>PrzyciskRB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR2</code></td><td><code>Przycisk R2</code></td><td><code>PrzyciskRT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><code>Przycisk R3</code></td><td><code>PrzyciskRS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonStart</code></td><td><code>Opcje przycisków</code></td><td><code>Przycisk Start</code></td></tr><tr><td><code>Enum.KeyCode.ButtonSelect</code></td><td><code>Pasek dotykowy przycisków</code> i <code>Przycisk Udostępnij</code></td><td><code>Przycisk wyboru</code></td></tr></tbody>
Kod klucza |
---|
Obrazy systemowe dla KeyCodes
Kiedy używasz Enum.KeyCode, które można lepiej reprezentować jako obraz, na przykład dla ImageLabel w interfejsie użytkownika, możesz użyć następujących ikonek dziedzictwa.Zaleca się jednak, abyś użył GetImageForKeyCode() jako bardziej nowoczesnej, wieloplatformowej metody odzyskiwania ikon kontrolera Xbox i PlayStation.
<th>Obraz</th><th>ID zasobu</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonX</code></td><td><img src="../../../assets/scripting/controls/xboxX.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxX.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonY</code></td><td><img src="../../../assets/scripting/controls/xboxY.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxY.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonA</code></td><td><img src="../../../assets/scripting/controls/xboxA.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxA.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonB</code></td><td><img src="../../../assets/scripting/controls/xboxB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxB.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadLeft</code></td><td><img src="../../../assets/scripting/controls/dpadLeft.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadLeft.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadRight</code></td><td><img src="../../../assets/scripting/controls/dpadRight.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadRight.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadUp</code></td><td><img src="../../../assets/scripting/controls/dpadUp.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadUp.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadDown</code></td><td><img src="../../../assets/scripting/controls/dpadDown.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadDown.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.ButtonSelect</code></td><td><img src="../../../assets/scripting/controls/xboxView.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxView.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.ButtonStart</code></td><td><img src="../../../assets/scripting/controls/xboxmenu.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxmenu.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><img src="../../../assets/scripting/controls/xboxLB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLB.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><img src="../../../assets/scripting/controls/xboxRB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRB.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.ButtonL2</code></td><td><img src="../../../assets/scripting/controls/xboxLT.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLT.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR2</code></td><td><img src="../../../assets/scripting/controls/xboxRT.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRT.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.ButtonL3</code></td><td><img src="../../../assets/scripting/controls/xboxLS.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLS.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><img src="../../../assets/scripting/controls/xboxRS.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRS.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Thumbstick1</code></td><td><img src="../../../assets/scripting/controls/xboxLSDirectional.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLSDirectional.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Thumbstick2</code></td><td><img src="../../../assets/scripting/controls/xboxRSDirectional.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRSDirectional.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Backspace</code></td><td><img src="../../../assets/scripting/controls/backspace.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/backspace.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Return</code></td><td><img src="../../../assets/scripting/controls/return.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/return.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.LeftShift</code></td><td><img src="../../../assets/scripting/controls/shift.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/shift.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.RightShift</code></td><td><img src="../../../assets/scripting/controls/shift.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/shift.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Tab</code></td><td><img src="../../../assets/scripting/controls/tab.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/tab.png</code></td></tr><tr><td><code>Enum.KeyCode.Apostrophe</code></td><td><img src="../../../assets/scripting/controls/apostrophe.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/apostrophe.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Comma</code></td><td><img src="../../../assets/scripting/controls/comma.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/comma.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Backquote</code></td><td><img src="../../../assets/scripting/controls/graveaccent.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/graveaccent.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Okres</code></td><td><img src="../../../assets/scripting/controls/period.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/period.png</code></td></tr><tr><td><code>Kumulacja.KeyCode.Space</code></td><td><img src="../../../assets/scripting/controls/spacebar.png" width="24"></img></td><td><code>rbxasset://textures/ui/Kontrolki/przestrzeń baru.png</code></td></tr></tbody>
Kod klucza |
---|
Parametry
Zwroty
GetSupportedGamepadKeyCodes
Funkcja ta zwraca tablicę KeyCodes, która jest wspierana przez gamepad związany z danym Enum.UserInputType .
Funkcja ta może być używana do określenia, które klawisze są wspierane, a które nie są wspierane przez połączoną konsolę.Aby określić, czy określony KeyCode jest wspierany, użyj UserInputService:GamepadSupports().
Jeśli wezwano nieistniejący lub nie połączony gamepad, ta funkcja zwróci pustą listę.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType z gamepada.
Zwroty
Przykłady kodu
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
Funkcja ta sprawdza, czy naciśnięto określony przycisk na określonym gamepadzie.Zwraca true jeśli gamepad ma wciśnięte określone button, w przeciwnym razie zwraca fałsz.
Prawidłowe typy wejść użytkownika
Wskazany gamepad powinien być jedną z następujących wartości enum typu wejścia użytkownika:
<tr><td>Enum.UserInputType.Gamepad1-8</td></tr>
Nazwa |
---|
Ważne klawiatury kluczowe
Wskazany przycisk powinien być jedną z następujących wartości enum KeyCodes:
<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.DPadDown</td></tr>
Nazwa |
---|
Można tego użyć, aby sprawdzić, czy konkretny przycisk, tak jak A, jest przytrzymywany. Na przykład:
local UserInputService = game:GetService("UserInputService")local button = Enum.KeyCode.ButtonAlocal gamepad = Enum.UserInputType.Gamepad1local isButtonHeld = UserInputService:IsGamepadButtonDown(gamepad, button)
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
- UserInputService:IsKeyDown() - Podobna metoda z innym użyciem: Aby sprawdzić, czy naciśnięto dany key na keyboard.
Parametry
The Enum.UserInputType z podanego gamepada.
The Enum.KeyCode z określonym przyciskiem.
Zwroty
Czy określony przycisk na gamepadzie na podanym gamepadzie jest naciśnięty, jest naciśnięty.
Przykłady kodu
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
Funkcja ta zwraca, czy użytkownik przytrzymuje klawisz związane z danym Enum.KeyCode .Zwraca true jeśli określony klucz zostanie naciśnięty lub false jeśli nie zostanie naciśnięty.
Można to użyć do sprawdzenia, czy naciśnięto określoną klucz, taką jak spacja, na przykład:
local UserInputService = game:GetService("UserInputService")local spaceHeld = UserInputService:IsKeyDown(Enum.KeyCode.Space)
Aby odzyskać listę wszystkich naciśniętych klawiszy przez użytkownika, użyj funkcji UserInputService:GetKeysPressed().
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
- Enum.UserInputType.IsGamepadButtonDown - Podobne wydarzenie z innym użyciem: Aby sprawdzić, czy naciśnięto dany button na gamepad.
Parametry
The Enum.KeyCode klucza.
Zwroty
Czy określony klucz jest przytrzymywany.
Przykłady kodu
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
Funkcja ta przyjmuje przycisk myszy Enum.UserInputType i zwraca bool, który wskazuje, czy jest obecnie naciśnięty.
Przycisk myszy sprawdzony zależy od wartości Enum.UserInputType przekazanej do funkcji jako argument. Na przykład:
local UserInputService = game:GetService("UserInputService")local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript."
Parametry
The Enum.UserInputType z przycisku myszy.
Zwroty
Czy dany przycisk myszy jest obecnie przytrzymywany.
Przykłady kodu
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
Funkcja ta zwraca true, jeśli określony Enum.UserInputType gamepad jest dozwolony do kontroli nawigacji i wyboru GuiObjects .
Jeśli chcesz ustawić gamepad nawigacyjny, możesz użyć UserInputService:SetNavigationGamepad(). Możesz także użyć UserInputService:GetNavigationGamepads() , aby uzyskać listę wszystkich gamepadów nawigacyjnych.
Na przykład kod poniżej sprawdza, czy gamepad1 jest jako gamepad nawigacyjny:
local UserInputService = game:GetService("UserInputService")if UserInputService:IsNavigationGamepad(UserInputType.Gamepad1) thenprint("Gamepad is a navigation gamepad!")elseprint("Gamepad is not a navigation gamepad!")end
Listę wszystkich połączonych gamepadów, niezależnie od nawigacji, można odzyskać za pomocą `UserInput/GetConnectedGamepads.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType z określonego gamepada.
Zwroty
Czy określony gamepad jest gamepadem nawigacyjnym.
RecenterUserHeadCFrame
Funkcja ta odśrodkowuje CFrame słuchawki VR do obecnego kierunku noszenia słuchawki przez użytkownika.Oznacza to, że obecna orientacja zestaw słuchawkowyjest ustawiona na CFrame.new() .
Użyj tej funkcji, aby przenieść słuchawki CFrame do centrum obszaru odtwarzania, jeśli wydają się być na dziwnym przesunięciu.
Zachowuje się to identycznie do funkcji Class.VRService``Class.VRService:RecenterUserHeadCFrame().
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zwroty
Przykłady kodu
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
Funkcja SetNavigationGamepad określa, czy określony Enum.UserInputType gamepad może przesuwać nawigator GUI.Gamepad, który może przesuwać nawigator GUI, jest uważany za gamepad nawigacyjny.
Jeśli argument włączony jest przekazany jako true, Gamepad może przesuwać nawigator GUI.Jeśli argument wynosi false, Gamepad nie może przesuwać nawigatora GUI.
Jeśli chcesz sprawdzić, czy określona konsola jest ustawiona jako konsola nawigacyjna, możesz użyć funkcji UserInputService:IsNavigationGamepad().Możesz także użyć UserInputService:GetNavigationGamepads() aby odzyskać listę wszystkich paseków nawigacyjnych.
Ponieważ UserInputService jest tylko po stronie klienta, ta funkcja może być używana tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType z określonego gamepada.
Czy określony gamepad może przesuwać nawigator GUI.
Zwroty
Przykłady kodu
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)
Zdarzenia
DeviceAccelerationChanged
Wydarzenie DeviceAccelerationChanged występuje, gdy użytkownik przesuwa urządzenie, które ma akcelerometr.
Akcelerometr to komponent znajdujący się w większości urządzeń mobilnych, który mierzy przyspieszenie (zmianę prędkości).
Aby określić, czy urządzenie użytkownika ma akcelerometr włączony, zobacz UserInputService.AccelerometerEnabled .
Wydarzenie to można wykorzystać do śledzenia ruchu urządzenia, które ma akcelerometr.Przykładowe użycie obejmuje przesuwanie postaci gracza, gdy urządzenie mobilne przyspiesza.
Ponadto to wydarzenie można używać wraz z UserInputService:GetDeviceAcceleration(), aby określić obecny ruch urządzenia użytkownika, jeśli urządzenie ma akcelerometr.
To wydarzenie uruchamia się tylko lokalnie - co oznacza, że tylko gracz, którego urządzenie się porusza, może korzystać z wydarzenia i będzie działać tylko w LocalScript .
Parametry
An InputObject , z UserInputType z "akcelerometrem" i Position , który pokazuje siłę grawitacji na każdej osi lokalnego urządzenia.
Przykłady kodu
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
Wydarzenie UserInputService.DeviceGravityChanged uruchamia się, gdy grawitacja urządzenieVector3 zmienia się na urządzeniu, które ma akcelerometer.
Wektor grawitacji urządzenia reprezentuje siłę grawitacji na każdym z osi X, Y i Z urządzenia.Choć grawitacja nigdy się nie zmienia, siła wywierana na każdej osi zmienia się, gdy urządzenie się obraca i zmienia orientację.Wartość siły wywierana na każdej osi jest wektorem jednostek w przedziale od -1 do 1.
Akcelerometr to komponent znajdujący się w większości urządzeń mobilnych, który mierzy przyspieszenie (zmianę prędkości).
Wydarzenie to można wykorzystać do określenia rzeczywistego kierunku siły grawitacji na urządzenieużytkownika.Można go nawet użyć do symulacji siły grawitacji na urządzeniu użytkownika w grze, tak jak na obiektach w grze (zobacz przykład poniżej).
Aby sprawdzić, czy urządzenie użytkownika ma włączony akcelerometr, zobacz UserInputService.AccelerometerEnabled .Jeśli urządzenie ma włączony akcelerometr, możesz użyć funkcji UserInputService:GetDeviceGravity(), aby uzyskać obecną siłę grawitacji na urządzeniu użytkownika.
Parametry
An InputObject , z właściwością InputObject.Position pokazującą siłę grawitacji na każdej osi lokalnego urządzenia.Pozycja ta może być użyta jako kierunek do określenia kierunku grawitacji względem urządzenie.
Przykłady kodu
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
Wydarzenie DeviceRotationChanged występuje, gdy użytkownik obraca urządzenie, które ma akcelerometr.
Gyroskop to komponent znajdujący się w większości urządzeń mobilnych, które wykrywają orientację i prędkość obrotową.
Wydarzenie jest przydatne przy śledzeniu orientacji urządzenia i sposobu zmian, gdy użytkownik obraca urządzenie.Aby określić obecną rotację urządzenia, możesz użyć funkcji UserInputService:GetDeviceRotation().
Aby sprawdzić, czy urządzenie użytkownika ma włączony akcelerometr i czy wydarzenie zostanie uruchomione, zobacz UserInputService.GyroscopeEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Parametry
An InputObject dostarczający informacje o rotacji urządzenie.InputObject.Position reprezentuje nową rotację wartością pozycyjną Vector3 i InputObject.Delta reprezentuje zmianę w rotacji w wartości pozycyjnej Vector3.
Przykłady kodu
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
Wydarzenie GamepadConnected występuje, gdy gamepad jest podłączony do klienta.
Ponieważ gra Roblox wspiera wiele kontrolerów, wydarzenie to jest przydatne, gdy połączone z wydarzeniem UserInputService.GamepadDisconnected śledzi, które kontrolery/gadżety są aktywne.Możesz także użyć UserInputService:GetConnectedGamepads(), aby znaleźć poprawną konsolę do użycia.
Poniższy przykład pokazuje przykład użycia śledzenia, gdy gamepad jest podłączony do klienta.
local UserInputService = game:GetService("UserInputService")
local function GamepadConnected(gamepad)
print("Player has plugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadConnected:Connect(GamepadConnected)
Jeśli chcesz zobaczyć, które urządzenia są podłączone, możesz użyć funkcji UserInputService:GetConnectedGamepads().
Ponieważ to wydarzenie wystrzeliwuje lokalnie, może być używane tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType z połączonego gamepada.
GamepadDisconnected
Wydarzenie GamepadDisconnected występuje, gdy gamepad jest odłączony.
Ponieważ gra Roblox wspiera wiele kontrolerów, wydarzenie to jest przydatne, gdy połączone z wydarzeniem UserInputService.GamepadConnected śledzi, które kontrolery/gadżety są aktywne.Możesz także użyć UserInputService:GetConnectedGamepads(), aby znaleźć poprawną konsolę do użycia.
Poniższy przykład pokazuje przykład użycia śledzenia, gdy gamepad jest odłączony od klienta.
local UserInputService = game:GetService("UserInputService")
local function GamepadDisconnected(gamepad)
print("Player has unplugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadDisconnected:Connect(GamepadDisconnected)
Ponieważ to wydarzenie wystrzeliwuje lokalnie, może być używane tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputType z odłączonego gamepada.
InputBegan
Wydarzenie InputBegan wystrzeliwuje się, gdy użytkownik zaczyna interakcję za pomocą urządzenia interfejsu człowiek-komputer (przycisk myszy w dół, dotknięcie początku, przycisk klawiatury w dół itp.).
Można go używać do śledzenia początku interakcji użytkownika, takich jak po raz pierwszy interakcja z elementem interfejsu graficznego, gamepadem itp.Nie rejestruje ruchów koła myszy.
To wydarzenie można używać wraz z UserInputService.InputChanged i UserInputService.InputEnded do śledzenia, kiedy rozpoczyna się wejście użytkownika, zmiany i kończy.
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Parametry
instancjaInputObject, która zawiera informacje o wejściu użytkownika.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie InputChanged występuje, gdy użytkownik zmienia sposób interakcji za pomocą urządzenia interfejsu człowiek-komputer (przycisk myszy w dół, dotknięcie początku, przycisk klawiatury w dół itp.).
Aby ignorować wydarzenia obsługiwane automatycznie przez Roblox, takie jak przewijanie w ScrollingFrame, sprawdź, czy argument gameProcessedEvent jest fałszywy.To wydarzenie można używać wraz z UserInputService.InputBegan i UserInputService.InputEnded, aby śledzić, kiedy rozpoczyna się wejście użytkownika, zmiany i kończy.
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Parametry
instancjaInputObject, która zawiera informacje o wejściu użytkownika.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie InputEnded występuje, gdy użytkownik przestaje interakcjonować za pomocą urządzenia interfejsu człowiek-komputer (przycisk myszy w dół, dotknięcie początku, przycisk klawiatury w dół itp.).Jest to przydatne, gdy śledzisz, kiedy użytkownik wypuści kluczklawiatury, przycisk myszy, wejście dotykowe itp.
To wydarzenie można używać wraz z UserInputService.InputBegan i UserInputService.InputChanged do śledzenia, kiedy rozpoczyna się wejście użytkownika, zmiany i kończy.
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Parametry
instancjaInputObject, która zawiera informacje o wejściu użytkownika.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie UserInputService JumpRequest występuje, gdy pojawi się żądanie skoku z klienta, na przykład gdy klient naciśnie spacji lub przycisk skoku na urządzeniu mobilnym.
To wydarzenie wystrzeliwuje się za każdym razem, gdy użytkownik próbuje wykonać swój skok Player.Character.Domyślne zachowanie odpowiada na prośbę o skok ustawiając właściwość gracza Humanoid.Jump na prawdę, co powoduje skok postaci gracza.
Wydarzenie może być używane do śledzenia każdego razu, gdy gracz chce skoczyć.Zamiast używać go, aby sprawić, że gracz skocze, powinien być używany do zmiany domyślnego zachowania skoku - na przykład wyłączenia skoku.
Na przykład kod poniżej drukuje „Skok” za każdym razem, gdy gracz wysyła prośbę o skok.
local UserInputService = game:GetService("UserInputService")
function onJumpRequest()
print("Jump!")
end
UserInputService.JumpRequest:Connect(onJumpRequest)
Ponieważ to wydarzenie wystrzeliwuje wielokrotnie dla pojedynczej prośbao skok, zaleca się użycie debounce.
Jeśli chcesz połączyć klawisze lub przyciski z innymi działaniami, rozważ użycie wydarzeń takich jak UserInputService:GetKeysPressed() i UserInputService.InputBegan lub ContextActionService.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Przykłady kodu
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
Wydarzenie UserInputService.LastInputTypeChanged uruchamia się za każdym razem, gdy klient zmienia sposób interakcji za pomocą urządzenieinterfejsu człowiek-komputer.(i.e.od MouseMovement do MouseWheel lub od Thumbstick1 do Thumbstick2).
Aby uzyskać wartość ostatniego wpisywaćwejścia, niezależnie od tego, czy się zmienił, możesz użyć funkcji UserInputService:GetLastInputType().
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Parametry
A Enum.UserInputType wskazujący ostatni wpisywaćwejścia.
Przykłady kodu
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
Akcja wskazania wystrzeliwuje się, gdy użytkownik wykonuje określoną akcjiwskazania. W szczególności przewijanie koła myszy.
Parametry
TextBoxFocusReleased
Wydarzenie TextBoxFocusReleased występuje, gdy klient traci skupienie na TextBox , zwykle gdy klient zatrzymuje wpisanie tekstu, naciskając powrót lub klikając/dotykając gdzie indziej na ekranie.
Na przykład kod poniżej drukuje nazwę TextBox tracącego koncentrację, gdy wydarzenie się uruchamia.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocusReleased(textbox)
print(textbox.Name)
end
UserInputService.TextBoxFocusReleased:Connect(TextBoxFocusReleased)
Można go używać obok UserInputService.TextBoxFocused, aby śledzić, kiedy TextBox zyskuje i traci koncentrację.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także
Parametry
TextBoxFocused
To wydarzenie wystrzeliwuje się, gdy uzyska się skupienie na TextBox, zwykle gdy klient kliknie/dotknie pola tekstowego, aby rozpocząć wpisywanie tekstu.Wystrzeliwuje to również, jeśli skupienie pola tekstowego jest skupione za pomocą TextBox:CaptureFocus() .
Na przykład kod poniżej drukuje nazwę TextBox skupioną, gdy wydarzenie się uruchamia.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocused(textbox)
print(textbox.Name)
end)
UserInputService.TextBoxFocused:Connect(TextBoxFocused)
Można go używać obok UserInputService.FocusReleased, aby śledzić, kiedy tekstowe pole zyskuje i traci skupienie.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także
Parametry
TouchDrag
Parametry
TouchEnded
Wydarzenie TouchEnded występuje, gdy użytkownik uwolnił palec z ekranu urządzeniez włączonym dotykiem, kończąc wpisywanie dotyku za pomocą urządzenie.
Wydarzenie to można wykorzystać do określenia, kiedy użytkownik przestaje dotykać ekranu swojego urządzenie.Można go połączyć z UserInputService.TouchStarted, aby określić, kiedy użytkownik zaczyna i kończy dotykanie ekranu.
Na przykład kod poniżej drukuje pozycję ekranu, w której użytkownik przestaje dotykać ekranu.
local UserInputService = game:GetService("UserInputService")
function TouchEnded(touch, gameProcessedEvent)
print("Touch ended at " .. tostring(touch.Position))
end
UserInputService.TouchEnded:Connect(TouchEnded)
Obiekt wejścia dotykowego jest taki sam obiekt wejścia przez cały czas trwania dotyku.Więc porównanie InputObjects, gdy są obiektami dotykowymi, jest ważne, aby określić, czy jest to ten sam palec.
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także:
Parametry
instancjaInputObject, która zawiera informacje o wejściu użytkownika.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wystrzeliwany, gdy użytkownik trzyma co najmniej jeden palec przez krótki czas na tej samej pozycji ekranu urządzenieWłączone dotknięcie.
Wydarzenie to można wykorzystać do określenia, kiedy użytkownik przytrzymuje palec na ekranie w grze GuiObject lub elementie.
Poniższy przykład drukuje state długie naciśnięcie, gdy użytkownik trzyma co najmniej jeden palec przez krótki czas na tej samej pozycji ekranu.Możliwe stany obejmują: Rozpocznij , Zmień , Zakończ , Anuluj i Nic.
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)
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled.
Można go połączyć z UserInputService.TouchStarted i UserInputService.TouchEnded, aby określić, kiedy użytkownik zaczyna i kończy dotykanie ekranu.
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także:
Parametry
The Enum.UserInputState of the gesture.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wystrzeliwuje, gdy użytkownik przesuwa palec na urządzenieTouchEnabled takim jak tablet lub smartfon.
To wydarzenie jest przydatne do śledzenia, czy użytkownik przesuwa palec po ekranie, a także gdzie użytkownik przesuwa palec.
Kod poniżej pokazuje dotknięcie przesuwające się z poprzedniej pozycji do nowej pozycji na urządzenieTouchEnabled.Zauważ, że InputObject.Position na przekazanym parametrze touch jest Vector3, ale zawiera tylko koordynaty X i Y; Z zawsze wynosi 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)
Połącz to wydarzenie z UserInputService.TouchStarted i UserInputService.TouchEnded w celu określenia, kiedy użytkownik zaczyna dotykać ekranu, jak jego palec się porusza podczas dotykania go, i kiedy przestaje dotykać ekranu.
Aby sprawdzić, czy urządzenie użytkownika wspiera dotyk i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także:
Parametry
instancjaInputObject, która zawiera informacje o wejściu użytkownika.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie TouchPan wystrzeliwuje się, gdy użytkownik przeciągnie co najmniej jeden palec na urządzenieTouchEnabled.
Wydarzenie to można wykorzystać do określenia, kiedy użytkownik przesuwa palcem po ekranie urządzenia z włączonym dotykiem - na przykład do obrotu Camera w skrypcie niestandardowej kamery.
Poniższy kod drukuje „Prędkość przesuwania dotyku” połączoną z prędkością dotknięcia użytkownika, gdy użytkownik przesuwa palcem po ekranie.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
print("Speed of touch drag: " .. tostring(velocity))
end)
Spójrz na inną przydatną funkcję UserInputService tutaj UserInputService.TouchRotate.
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także:
Parametry
Matryca Vector2 obiektów, wskazująca pozycje dotyków (np. palców) zaangażowanych w gest.
Rozmiar gestu patelni od początku do końca (w pikselach).
Prędkość gestu panoramy (w pikselach) na sekundę.
The Enum.UserInputState of the gesture.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wystrzeliwany, gdy użytkownik umieszcza i przesuwa dwa palce na ekranie urządzenieTouchEnabled.
Na instancjaponiższy kod drukuje, jak dużo zmieniła się skala przysłonięcia kamery od początku dotknięcia.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPinch:Connect(function(touchPositions, scale, velocity, state, gameProcessedEvent)
print("Scale difference since beginning of pinch: " .. tostring(scale))
end)
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie wystrzeliwuje tylko wtedy, gdy okno klienta Roblox jest w fokusie.Na przykład, wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także:
Parametry
Matryca Vector2s, wskazująca pozycję ekranu, w pikselach, palców zaangażowanych w gest przesuwania.
Wielkość skurczenia od początku do końca (w pikselach) podzielona przez pozycje skurczenia początkowego.
Prędkość gestu przesuwania (w pikselach) na sekundę.
The Enum.UserInputState of the gesture.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie TouchRotate występuje, gdy użytkownik obraca dwa palce na urządzenieTouchEnabled.
Na przykład następujący kod drukuje, jak dużo kamera się obróciła od początku rotacji dotykowej.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchRotate:Connect(function(touchPositions, rotation, velocity, state, gameProcessedEvent)
print("Camera has rotated " .. tostring(rotation) .. " degrees!")
end)
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Główne skrypty, które kontrolują kamerę użytkownika na urządzeniu mobilnym, używają kodu, który działa podobnie do tego wydarzenia.Najlepszą praktyką dla tego wydarzenia jest jego użycie podczas tworzenia systemu kamery mobilnej, aby zastąpić domyślne skrypty rdzenia.
Zobacz także:
Parametry
Liczba stopni, w jakich ruch się obrócił od początku ruchu.
Zmiana w obrocie (w stopniach) podzielona przez czas trwania zmiany (w sekundach).
The Enum.UserInputState of the gesture.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie TouchStarted uruchamia się, gdy użytkownik umieści palec na urządzenieTouchEnabled, rozpoczynając wpisywanie dotyku za pomocą urządzenie.
Wydarzenie to można wykorzystać do określenia, kiedy użytkownik zaczyna dotykać ekranu swojego urządzenie.Można go połączyć z UserInputService.TouchEnded, aby określić, kiedy użytkownik zaczyna i kończy dotykanie ekranu.
Obiekt wejścia dotykowego jest taki sam obiekt wejścia przez cały czas trwania dotyku.Więc porównanie InputObjects, gdy są obiektami dotykowymi, jest ważne, aby określić, czy jest to ten sam palec.
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także:
Parametry
instancjaInputObject, która zawiera informacje o wejściu użytkownika.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie TouchSwipe występuje, gdy użytkownik przesuwa palce po urządzenieTouchEnabled.
Wydarzenie to można wykorzystać do określenia, kiedy użytkownik przesuwa palce po ekranie swojego urządzenia i kierunku, w którym przesuwał.
Aby uzyskać bardziej precyzyjne śledzenie ruchu dotykowego, użyj UserInputService.TouchMoved
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Zobacz także:
Parametry
An Enum.SwipeDirection, wskazujący kierunek, w którym użytkownik przesuwał.
Liczba dotknięć (np. palców) zaangażowanych w gest.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie TouchTap wystrzeliwuje się, gdy użytkownik dotknie/dotknie palcem ekranu na urządzenieTouchEnabled.
To wydarzenie zostanie uruchomione niezależnie od tego, czy użytkownik dotknie/dotknie świata gry lub elementu GuiObject.Jeśli szukasz wydarzenia, które wysyła się tylko wtedy, gdy użytkownik dotknie/dotknie świata gry, użyj UserInputService.TouchTapInWorld.
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Parametry
Zbiór Vector2 obiektów, który wskazuje pozycję palców zaangażowanych w gest dotknięcia.
Wskazuje, czy silnik gry obserwował wewnętrznie ten wejściowy sygnał i działał na nim.Ogólnie odnosi się to do przetwarzania interfejsu użytkownika, więc jeśli przycisk został dotknięty lub kliknięty z tego wpisu, gameProcessedEvent byłby true.To samo dotyczy wydarzeń wejściowych połączonych za pomocą ContextActionService .
Przykłady kodu
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
Wydarzenie TouchTapInWorld wystrzeliwuje się, gdy użytkownik dotknie/dotknie palcem ekranu na urządzenieTouchEnabled.Wysyłany jest, gdy użytkownik kliknie w świat gry.
Wydarzenie to można wykorzystać do określenia, kiedy użytkownik dotknie ekranu i nie dotknie elementu GuiObject.Jeśli użytkownik naciśnie element GUI, UserInputService.TouchTap uruchomi zamiast TouchTapInWorld.
Aby sprawdzić, czy urządzenie użytkownika jest włączone do dotyku i czy zdarzenia dotykowe zostaną uruchomione, zobacz UserInputService.TouchEnabled .
To wydarzenie uruchamia się tylko wtedy, gdy okno klienta Roblox jest w focusie. Na przykład wejścia nie zostaną zarejestrowane, gdy okno zostanie zmniejszone.
Ponieważ strzela tylko lokalnie, może być używany tylko w LocalScript.
Zobacz także:
Parametry
Czy użytkownik kliknął element interfejsu graficznego.
Przykłady kodu
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
Wydarzenie UserInputService WindowFocusReleased występuje, gdy okno klienta Roblox traci focus - zwykle gdy klient Roblox jest zmniejszony przez użytkownika
Na przykład kod poniżej drukuje "Skupienie okna uwolnione" za każdym razem, gdy klient Roblox traci skupienie.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocusReleased:Connect(function()
print("Window focus released")
end)
To wydarzenie można używać wraz z UserInputService.WindowFocused, aby śledzić, czy klient Roblox jest aktywnie skoncentrowany na ekranie użytkownika.
Ponieważ strzela tylko lokalnie, może być używany tylko w LocalScript.
Przykłady kodu
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
Wydarzenie skupione na oknie wystrzeliwuje się, gdy okno klienta Roblox uzyska focus - zwykle gdy klient Roblox jest maksymalizowany/aktywnie otwarty na ekranie użytkownika.
Na przykład kod poniżej drukuje "Skupiono okno" za każdym razem, gdy klient Roblox zyskuje skupienie.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocused:Connect(function()
print("Window focused")
end)
To wydarzenie można używać wraz z UserInputService.WindowFocusReleased, aby śledzić, czy klient Roblox jest aktywnie skoncentrowany na ekranie użytkownika.
Ponieważ to wydarzenie wystrzeliwuje się tylko lokalnie, można go używać tylko w LocalScript.
Przykłady kodu
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)