UserInputService

Artık kullanılmayanları göster

*Bu içerik, yapay zekâ (beta) kullanılarak çevrildi ve hatalar içerebilir. Sayfayı İngilizce görüntülemek için buraya tıkla.

Oluşturulamaz
Hizmet
Çoğaltılmamış

UserInputService bir kullanıcının cihazında mevcut olan farklı giriş türlerini tespit etmek ve yakalamak için kullanılan bir hizmettir.

Bu hizmetin ana amacı, oyun konsolları, dokunma ekranları ve klavyeler gibi çok sayıda mevcut giriş türüyle işbirliği yapabilen deneyimlere izin vermektir.Cihaza bağlı olarak farklı eylemler yürütmesine izin verir LocalScript ve bununla birlikte, son kullanıcı için en iyi deneyimi sağlar.

Bu hizmetin bazı kullanımları, kullanıcıların GUI'ler, araçlar ve diğer oyun durumlarıyla etkileşim kurduklarında kullanıcı girişini algılamayı içerir.Kullanıcı girişini tespit etmek için, hizmet bir hizmet olayı aramalıdır.Örneğin, hizmet, kullanıcının bir mobil cihazın ekranına dokunduğunda UserInputService.TouchStarted , veya bir Xbox kontrolörü gibi bir oyun konsolunu cihazına bağladığında UserInputService.GamepadConnected kullanarak olayları tespit edebilir.

Bu hizmet yalnızca istemci tarafında olduğundan, yalnızca bir LocalScript veya bir ModuleScript tarafından gerekli olduğunda çalışacaktır LocalScript.KullanıcıGirişServisi sadece istemci tarafı olduğundan, oyundaki kullanıcılar sadece kendi girişlerini tespit edebilir - ve diğerlerin girişini değil.

Ayrıca bakın ContextActionService , işlevleri çoklu kullanıcı girişlerine bağlama izin veren bir hizmet.

Kod Örnekleri

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

UserInputService

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

Özet

Özellikler

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Kullanıcının cihazının bir hızlandırıcıya sahip olup olmadığını tanımlar.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Kullanıcı tarafından kullanılan cihazın mevcut bir oyun kolu olup olmadığını tanımlar.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Kullanıcının cihazının bir jiroskopa sahip olup olmadığını tanımlar.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Kullanıcının cihazının bir klavyeye sahip olup olmadığını tanımlar.

  • Kullanıcının mouse'unun özgürce hareket edebileceği veya kilitli olacağını belirler.

  • Çoğaltılmamış
    Paralel oku

    Kullanıcının Mouse 'sindeki delta (değişim) çıkısını ölçeklendirir.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Kullanıcının cihazının bir fareye sahip olup olmadığını tanımlar.

  • MouseIcon:ContentId
    Paralel oku

    Kullanıcı fare simgesi olarak kullanılan görüntünün içeriği ID'si.

  • Mouse simgesinin görülebilir olup olmadığını belirler.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Ekran üzeri klavyenin konumunu belirler.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Ekran üzeri klavyenin boyutunu belirler.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Ekranda bir klavyenin şu anda kullanıcının ekranında görülebilir olup olmadığını tanımlar.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Kullanıcının mevcut cihazının dokunmatik bir ekrana sahip olup olmadığını tanımlar.

  • Salt Okunur
    Çoğaltılmamış
    Paralel oku

    Kullanıcının sanal gerçeklik kulaklıkkullandığını gösterir.

Yöntemler

Etkinlikler

Özellikler

AccelerometerEnabled

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, kullanıcının cihazının bir hızlandırıcıya sahip olup olmadığını tanımlar

Bir hızlandırıcı, hızlanmayı ölçen çoğu mobil cihazda bulunan bir bileşendir (hız değişimi).

Örneğin, aşağıdaki kod parçacığı, kullanıcının cihazının bir hızlandırıcıya sahip olup olmadığını nasıl kontrol edeceğini gösterir.


local UserInputService = game:GetService("UserInputService")
local accelerometerEnabled = UserInputService.AccelerometerEnabled
if accelerometerEnabled then
print("Accelerometer enabled!")
else
print("Accelerometer not enabled!")
end

Cihazın bir hızlandırıcısı varsa, UserInputService:GetDeviceAcceleration() işlevini kullanarak veya cihazın hızlandırması değiştiğinde UserInputService.DeviceAccelerationChanged etkinliğini izleyerek mevcut hızlandırmasını alabilirsiniz.

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Kod Örnekleri

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

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

Move a Ball using the Accelerometer

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

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

GamepadEnabled

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, bir kullanıcı tarafından kullanılan cihazın mevcut bir oyun kolu olup olmadığını tanımlar.Oyun konsolları mevcutsa, bir liste bağlı oyun konsolları almak için UserInputService:GetConnectedGamepads() kullanabilirsiniz.

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Kod Örnekleri

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

How to Set the Active Gamepad for Input

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

GyroscopeEnabled

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, kullanıcının cihazının bir jiroskopa sahip olup olmadığını tanımlar.

Bir jiroskop, yön ve dönme hızını algılayan çoğu mobil cihazda bulunan bir bileşendir.

Bir kullanıcının cihazı bir jiroskopa sahipse, UserInputService:GetDeviceRotation() fonksiyonunu ve UserInputService.DeviceRotationChanged etkinliğini kullanarak oyununuza dahil edebilirsiniz.


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

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Kod Örnekleri

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

KeyboardEnabled

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, kullanıcının cihazının bir klavyeye sahip olup olmadığını tanımlar.Bu özellik, kullanıcının cihazında mevcut bir klavye varsa true ve yoksa false dır.

Kullanıcının mevcut bir klavyeye sahip olup olmadığını belirlemek için kullanılabilir - ki bu, klavye girişi kontrol etmek istiyorsanız önemli olabilir UserInputService:IsKeyDown() veya UserInputService:GetKeysPressed() klavye girişi kontrol etmek için kullanabilirsiniz.

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Kod Örnekleri

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

Check if Keyboard is Enabled

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

MouseBehavior

Paralel oku

Bu özellik, kullanıcının mouse'unun Enum.MouseBehavior enum'e göre nasıl davrandığını ayarlar. Üç değere ayarlanabilir:

Bu özelliğin değeri, etkinlik izleme fare hareketinin hassasiyetini etkilemez.Örneğin, GetMouseDelta aynı Vector2 ekran pozisyonunu piksel olarak geri döndürür, farenin kilitli olup olmadığına bakılmaksızın kullanıcının ekranında özgürce hareket edebilir.sonuç, kamerayı kontrol eden varsayılan kodlar bu özellikten etkilenmez.

Bu özellik, oyuncunun sağ fare düğmesi aşağıda olmadığında etkinleştirilen bir ile geçersiz kılınır, eğer oyuncunun sağ fare düğmesi aşağıda değilse.

Fare kilitliyse, UserInputService.InputChanged oyuncu fareyi hareket ettirdiğinde hala ateşlenecek ve oyuncunun hareket ettirdiği Delta'dan geçecektir.Ayrıca, oyuncu oyundan atılırsa, fare zorla kilidi açılacaktır.

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Kod Örnekleri

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

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

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

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

Create a Binoculars Script

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

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

MouseDeltaSensitivity

Çoğaltılmamış
Paralel oku

Bu özellik, kullanıcının Mouse duyarlılığını belirler.

Hassasiyet, fiziksel fare hareketinin oyun içi fare hareketine dönüştürülebilir derecesini belirler.Bu, hassas olayların fare hareketini nasıl izlediğini ayarlamak için kullanılabilir, örneğin GetMouseDelta , fare hareketine.

Bu özellik, fare simgesinin hareketini etkilemez.Ayrıca, müşterinin Ayarları menüsündeki Ayarlar sekmesinde bulunan Kamera Hassasiyeti ayarını da etkilemez, bu da olay izleme fare hareketinin hassasiyetini ayarlar.

Bu özelliğin maksimum değeri 10 ve minimum değeri 0'dır.Daha düşük bir değer daha düşük duyarlılığa ve daha yüksek bir değer daha yüksek duyarlılığa karşılık gelir.

Hassasiyet 0 olduğunda, fare hareketini izleyen olaylar hala ateş edecek, ancak fare konumundaki değişikliği gösteren tüm parametreler ve özellikler Vector2.new() veya Vector3.new() durumunda InputObject.Delta dönecek.Örneğin, GetMouseDelta daima dönecektir (0, 0).

Kod Örnekleri

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

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

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

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

Create a Binoculars Script

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

MouseEnabled

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, kullanıcının cihazının bir fareye sahip olup olmadığını tanımlar.Bu özellik, kullanıcının cihazında mevcut bir fare var olduğunda true ve yok olduğunda false dir.


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

Bunu UserInputService fare işlevleri gibi UserInputService:GetMouseLocation() kullanmadan önce kontrol etmek önemlidir.

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Kod Örnekleri

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

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

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

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

Create a Binoculars Script

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

MouseIcon

ContentId
Paralel oku

The MouseIcon özelliği, işaret olarak kullanılan görüntüyü belirler.Boşsa, varsayılan bir ok kullanılır.Kurma işaretleyici bir ImageButton , TextButton , TextBox veya ProximityPrompt gibi belirli UI nesnelerinin üzerinde gezinirken, bu görüntü geçersiz kalacak ve geçici olarak göz ardı edilecektir.

Okutucuyu tamamen gizlemek için, transparan bir görüntü kullanmayın , yerine UserInputService.MouseIconEnabled false'a ayarlayın.

Kod Örnekleri

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

UserInputService.MouseIcon

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

MouseIconEnabled

Paralel oku

Bu özellik, Mouse simgesinin görülebilir olup olmadığını belirler; true fare simgesi görülebilir olduğunda, false değil.

Örneğin, aşağıdaki kod parçacığı fare'un simgesini gizler.


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

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Kod Örnekleri

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

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

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

Hide Mouse During Keyboard Input

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

OnScreenKeyboardPosition

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, ekranda görünen klavyenin piksel cinsinden konumunu tanımlar. Klavyenin konumu görünür olmadığında Vector2.new(0, 0) dır.

As sadece istemci tarafında olduğundan, bu özellik yalnızca bir veya ile kullanılabilir .

Ayrıca bakın OnScreenKeyboardVisible ve OnScreenKeyboardSize .

Kod Örnekleri

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

UserInputService.OnScreenKeyboardPosition

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

OnScreenKeyboardSize

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, ekranda görünen klavyenin piksel cinsinden boyutunu tanımlar. Klavyenin boyutu görünür olmadığında Vector2.new(0, 0) dır.

As sadece istemci tarafında olduğundan, bu özellik yalnızca bir veya ile kullanılabilir .

Ayrıca bakın OnScreenKeyboardVisible ve OnScreenKeyboardPosition .

OnScreenKeyboardVisible

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, ekranda bir klavyenin şu anda kullanıcının ekranında görülebilir olup olmadığını tanımlar.

As sadece istemci tarafında olduğundan, bu özellik yalnızca bir veya ile kullanılabilir .

Ayrıca bakın OnScreenKeyboardSize ve OnScreenKeyboardPosition .

TouchEnabled

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, kullanıcının mevcut cihazının dokunmatik bir ekrana sahip olup olmadığını tanımlar.

Özellik, kullanıcının cihazının dokunmatik bir ekrana sahip olup olmadığını belirlemek ve dolayısıyla dokunma olaylarının ateşleneceğini belirlemek için kullanılır.TouchEnabled true ise, UserInputService.TouchStarted ve UserInputService.TouchEnded gibi KullanıcıGirişHizmeti etkinliklerini kullanarak bir kullanıcının cihazının ekranına dokunmaya başladığı ve durduğu anı izleyebilirsiniz.

Aşağıdaki kod parçacığı, kullanıcının cihazının dokunmatik bir ekrana sahip olup olmadığını basar.


local UserInputService = game:GetService("UserInputService")
if UserInputService.TouchEnabled then
print("The user's device has a touchscreen!")
else
print("The user's device does not have a touchscreen!")
end

Ayrıca bakın:

Kod Örnekleri

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

VREnabled

Salt Okunur
Çoğaltılmamış
Paralel oku

Bu özellik, kullanıcının sanal gerçeklik (VR) cihazı kullandığını tanımlar.

VR cihazı etkinleştirildiyse, yerleşimi ve hareketini UserInputService:GetUserCFrame() gibi işlevler aracılığıyla etkileştirebilirsiniz.Ayrıca UserInputService.UserCFrameChanged etkinliğini kullanarak VR cihaz hareketine tepki verebilirsiniz.


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

As UserInputService yalnızca istemci tarafında olduğundan, bu özellik yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Kod Örnekleri

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

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

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

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

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

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

VR Head Tracking

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

Yöntemler

GamepadSupports

Bu işlev, verilen Enum.UserInputType oyun kolu, verilen Enum.KeyCode ile eşleşen bir düğme desteklediğini döndürür.Bu işlev, geçerli oyun kolu girişlerini belirlemek için kullanılır.

Hangi Enum.UserInputType oyun konsollarının bağlı olduğunu belirlemek için, UserInputService:GetConnectedGamepads() kullanın.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadNum: Enum.UserInputType

Oyun kolu Enum.UserInputType 'inin.

Varsayılan değer: ""
gamepadKeyCode: Enum.KeyCode

Soruşturulan düğmenin Enum.KeyCode 'si.

Varsayılan değer: ""

Dönüşler

Verilen oyun kolu, verilen Enum.KeyCode ile eşleşen bir düğmeyi destekliyor mu?

Kod Örnekleri

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

Binding Functions to Gamepad Controls

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

GetConnectedGamepads

Bu işlev şu anda bağlı olan bir dizi Enum.UserInputType oyun konsolunu döndürür.Eğer oyun konsolları bağlanmazsa, bu dizi boş olacaktır.Ayrıca, sadece oyun konsolları olan UserInputType nesnelerini döndürür.durum, bu etkinlik bağlı bir Gamepad1 nesnesi döndürecek, ancak bir Klavye nesnesi değil.

Örneğin, aşağıdaki kod parçacığı bağlı oyun konsollarını alır ve connectedGamepads adlı değişkende saklar.


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

Belirli bir oyun kolu bağlı olup olmadığını kontrol etmek için UserInputService:GetGamepadConnected() kullanın.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:


Dönüşler

Kullanıcının cihazına bağlı oyun konsollarına karşılık gelen bir dizi UserInputTypes .

Kod Örnekleri

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

How to Set the Active Gamepad for Input

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

GetDeviceAcceleration

GetDeviceAcceleration işlevi, kullanıcının cihazının mevcut hızlandırma oranını belirler.Cihazın mevcut hızlanmasını tanımlayan bir InputObject döndürür, ki bu da cihazın hızlanmasını tanımlar.

Bunun çalışması için, kullanıcının cihazının bir hızlandırıcısı aktif olmalıdır.Bir kullanıcının cihazının bir hızlandırıcıya sahip olup olmadığını kontrol etmek için, UserInputService.AccelerometerEnabled özelliğini kontrol edebilirsiniz.

Kullanıcının cihazının hızlandırma değişikliklerinin yerine izlemek istiyorsanız, UserInputService.DeviceAccelerationChanged etkinliğini kullanabilirsiniz.

Yalnızca yerel olarak ateş olduğundan, sadece bir LocalScript içinde kullanılabilir.


Dönüşler

Kod Örnekleri

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

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

Print Device Acceleration

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

GetDeviceGravity

Bu işlev, cihazın mevcut yerçekim vektörünü tanımlayan bir InputObject döndürür.

Yerçekimi vektörü, cihazın yerçekimi gücüne ilişkin gerçek dünya odaklı yönüyle belirlenir.durum, bir cihaz mükemmel bir şekilde dik (portre) ise, yerçekimi vektörü Vector3.new(0, 0, -9.18) dir.Cihazın sol tarafı aşağı işaret ediyorsa, vektör Vector3.new(9.81, 0, 0) olur.Son olarak, cihazın arkası aşağı işaret ediyorsa, vektör Vector3.new(0, -9.81, 0) dir.

Bu işlev, kullanıcının cihazının oyun içinde yerçekimine etki etmesini veya bir top gibi oyun içi nesneleri hareket ettirmesini etkinleştirmek için kullanılabilir.

Yer çekimi yalnızca bir gyroskop ile etkinleştirilmiş bir cihaz kullanan oyuncular için izlenir - mobil bir cihaz gibi.

Bir kullanıcının cihazının bir jiroskopu var olup olmadığını kontrol etmek için, UserInputService.GyroscopeEnabled değerini kontrol edin.Cihazda bir jiroskop aktifse, kullanıcının cihazındaki yerçekimi gücünün değiştiği zamanı izlemek için UserInputService.DeviceGravityChanged etkinliğini de kullanabilirsiniz.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.


Dönüşler

Kod Örnekleri

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

Moving Objects with the Gyroscope

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

GetDeviceRotation

Bu işlev bir InputObject ve bir CFrame dönen cihazın mevcut dönme vektörünü tanımlayan bir döndürür.

Bunun bir InputObject ile ateş edilmesi gerekir.Giriş nesnesinin Pozisyon özelliği, her yerel cihaz eksenindeki toplam dönüşü izleyen bir Enum.InputType.Gyroscope dır.

Cihaz dönüşü yalnızca gyroscope ile etiketli cihazlarda izlenebilir.

Bu işlev yerel olarak ateş olduğundan, sadece bir LocalScript içinde kullanılabilir.


Dönüşler

İki özellik içeren bir tupl:

  1. Delta özelliği, son olarak gerçekleşen dönüş miktarını tanımlar
  2. CFRam, cihazın varsayılan referans çerçevesine göre mevcut dönüşüdür.

Kod Örnekleri

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

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

Print Device Rotation

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

GetFocusedTextBox

Bu işlev, müşterinin şu anda odaklandığı TextBox döndürür.Bir TextBox kullanıcı tarafından manuel olarak seçilebilir veya TextBox:CaptureFocus() fonksiyonu kullanılarak seçim zorlaştırılabilir.Eğer hiçbir TextBox seçilmezse, bu işlev nil döndürecektir.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın

Dönüşler

GetGamepadConnected

Bu işlev, verilen Enum.UserInputType ile bir oyun kolu klienteye bağlı olup olmadığını döndürür.

Bu, belirli bir oyun kolu, örneğin 'Gamepad1''in, istemci cihazına bağlı olup olmadığını kontrol etmek için kullanılabilir.

Tüm bağlı oyun konsollarının bir listesini almak için UserInputService:GetConnectedGamepads() kullanın.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadNum: Enum.UserInputType

Soruşturulan oyun kolu Enum.UserInputType 'nin.

Varsayılan değer: ""

Dönüşler

Bir oyun kolu, Enum.UserInputType ile bağlantılı olup olmadığı.

Kod Örnekleri

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

Check Whether a Gamepad is Connected

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

GetGamepadState

Bu işlev, verilen Enum.UserInputType oyun kolu üzerindeki tüm mevcut girişler için bir dizi InputObjects döndürür, her girişin son giriş durumunu temsil eden.

Bağlı oyun konsollarının UserInputTypes 'sini bulmak için, UserInputService:GetConnectedGamepads() kullanın.

Bu işlev yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadNum: Enum.UserInputType

Soruşturulan oyun kolu ile eşleşen Enum.UserInputType .

Varsayılan değer: ""

Dönüşler

Verilen oyun konsoluna tüm mevcut girişlerin mevcut durumunu temsil eden bir dizi InputObjects .

GetImageForKeyCode

ContentId

Bu yöntem talep edilen Enum.KeyCode alır ve şu anda bağlı olan oyun konsolu cihazı için ilişkili görüntüyü döndürür (Xbox, PlayStation ve Windows sınırlı).Bu, bağlı kontrolör bir Xbox One kontrolörü ise, kullanıcının Xbox varlıklarını gördüğü anlamına gelir.Benzer şekilde, bağlı cihaz bir PlayStation kontrolörü ise, kullanıcı PlayStation varlıklarını görür.Özel varlıklar kullanmak istiyorsanız, bakın GetStringForKeyCode() .

Parametreler

keyCode: Enum.KeyCode

İlgili görüntüyü almak için kullanılacak Enum.KeyCode .

Varsayılan değer: ""

Dönüşler

ContentId

Geri döndürülen görüntü varlığı ID'si.

Kod Örnekleri

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

UserInputService - Get Image For KeyCode

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

GetKeysPressed

Bu işlev, şu anda basılan anahtarlarla ilişkili bir dizi InputObjects döndürür.

Bu dizi, hangi anahtarların şu anda basıldığını belirlemek için InputObject.KeyCode değerlerini kullanarak döngülenebilir.

Belirli bir anahtarın basılıp basılmadığını kontrol etmek için UserInputService:IsKeyDown() kullanın.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.


Dönüşler

Şu anda basılan anahtarlarla ilişkili bir dizi InputObjects .

Kod Örnekleri

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

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

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

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

Double Jump Key Combo

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

GetLastInputType

Bu işlev, kullanıcının en yeni girişiyle ilişkili 'Enum.UserInputType' döndürür.

Örneğin, kullanıcının önceki girişi boşluk tuşuna basıyorsa, Enum.UserInputType döndürülecek 'Klavye' olurdu.

The UserInputService.LastInputTypeChanged etkinliği, kullanıcı tarafından değiştirilen son Enum.UserInputType kullanıldığında izlenebilir.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.


Dönüşler

Kullanıcının en yeni girişiyle ilişkili Enum.UserInputType .

Kod Örnekleri

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

UserInputService:GetLastInputType

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

GetMouseButtonsPressed

Bu işlev, şu anda basılmakta olan fare düğmelerine karşılık gelen bir dizi InputObjects döndürür.

Bu işlev tarafından izlenen fare düğmeleri şunları içerir:


<td>Açıklama</td>
</tr>
</thead>
<tr>
<td>Fare Tuşu1</td>
<td>Sol fare düğmesi.</td>
</tr>
<tr>
<td>Fare Tuşu 2</td>
<td>Sağ fare düğmesi.</td>
</tr>
<tr>
<td>Fare Tuşu 3</td>
<td>Orta fare düğmesi.</td>
</tr>
Adı

Kullanıcı, işlev çağrıldığında herhangi bir fare düğmesine basmıyorsa, boş bir dizi döndürecektir.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.


Dönüşler

Şu anda basılı tutulan fare düğmlerine karşılık gelen bir dizi InputObjects .

Kod Örnekleri

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

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

Check which MouseButtons are Pressed

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

GetMouseDelta

Bu işlev, son gösterilen çerçevede oyuncunun Mouse konumunun değişimini, piksel olarak, bir Vector2 olarak döndürür.Bu işlev yalnızca fare UserInputService.MouseBehavior özelliği kullanılarak kilitlenmişse çalışır.Fare kilitli değilse, döndürülen Vector2 değerler sıfır olacaktır.

farehassasiyeti, müşterinin ayarlarında ve UserInputService.MouseDeltaSensitivity belirlenen, sonuçetkileyecektir.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.


Dönüşler

farehareketinde değişiklik.

Kod Örnekleri

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

Getting Mouse Delta

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

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

GetMouseLocation

Bu işlev, oyuncunun Vector2 ının mevcut ekran konumunu temsil eden bir Mouse ı piksel olarak üst sol köşeye göre geri döndürür.Bu, en üst sol ve en alt sağ yerleşimleri almak için Enum.ScreenInsets ; almak için GuiService:GetGuiInset() 'yi arayın.

Fare işaretçisinin konumu ekranın dışında ise veya oyuncunun cihazında bir fare yoksa, döndürülen değer belirlenemeyecektir.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.


Dönüşler

Farenin mevcut ekran konumunu temsil eden bir Vector2 pikseldeki,

Kod Örnekleri

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

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

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

Move GUI To Mouse Location

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

GetNavigationGamepads

Bu işlev, bağlı ve GUI navigasyonu için etkinleştirilmiş bir dizi oyun kolu UserInputTypes.Bu liste öncelik sırasında azalan bir düzende ve bu da demektir ki hangi oyun kolu navigasyon kontrolüne sahip olmalıdır belirlemek için tekrarlanabilir.

Bağlı bir oyun kolu, yalnızca navigasyon GUI'lerini kontrol eden oyun kolu olup olmadığına karar verir.Bu, navigasyon denetimleretkilemez.

Çünkü UserInputService sadece istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:


Dönüşler

Öncelik sırasına göre GUI navigasyonu için kullanılabilecek bir dizi UserInputTypes öncelikli olarak düşen.

GetStringForKeyCode

GetStringForKeyCode bir kullanıcının belirli bir Enum.KeyCode girmesi için basması gereken bir anahtarı temsil eden bir dize döndürür, klavye düzenini göz önünde bulundurarak.Bazı değiştiricilerin tutulması gereken anahtar kodlar için, bu işlev anahtarı değiştiricinin yanında basılacak şekilde geri döndürür.Daha fazla açıklama için aşağıdaki örnekleri görün.

QWERTY klavye düzeni olmayan Roblox'u kullanırken, anahtar kodlar eşdeğer QWERTY konumlara yönlendirilir.Örneğin, AZERTY klavyesine basmak A sonucunda ortaya çıkar Enum.KeyCode.Q.Bu eşleştirme, deneyim UI öğeleriyle ilgili eşleşmeyen bilgilere yol açabilir.Örneğin, "Haritayı açmak için M bas" AZERTY klavyede yanlıştır; QWERTY'deki M ile aynı konumda olması gereken "Haritayı açmak için ? " gerekir.Bu işlev, QWERTY klavye düzenleri kullanılırken basılacak gerçek anahtarı sağlayarak bu sorunu çözer.


local UserInputService = game:GetService("UserInputService")
local textLabel = script.Parent
local mapKey = Enum.KeyCode.M
textLabel.Text = "Press " .. UserInputService:GetStringForKeyCode(mapKey) .. " to open the map"
QWERTY Klavyesi üzerindeki Örnekler

<th>Geri Dönüş Değeri</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'in</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>2</code> çünkü <code>@</code> ile yazılmıştır <kbd>Shift</kbd><kbd>2</kbd></td>
</tr>
</tbody>
Anahtar Kodu
AZERTY Klavyesi Üzerindeki Örnekler

<th>Geri Dönüş Değeri</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'in</code></td>
<td><code>=</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.At</code></td>
<td><code>É</code></td>
</tr>
</tbody>
Anahtar Kodu
Oyun Konsolu Kullanımı

GetStringForKeyCode() en yakın bağlı oyun kolu için Enum.KeyCode için yapılan dizilim dizesini geri verir.Bağlı kontrolör desteklenmiyorsa, işlev talep edilen anahtar kodu için varsayılan dize dönüşümünü döndürür.

Aşağıdaki örnek, özel varlıkları ButtonA için nasıl haritalayabileceğinizi gösterir:


local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappings = {
ButtonA = "rbxasset://BUTTON_A_ASSET", -- Replace with the desired ButtonA asset
ButtonCross = "rbxasset://BUTTON_CROSS_ASSET" -- Replace with the desired ButtonCross asset
}
local mappedKey = UserInputService:GetStringForKeyCode(key)
local image = mappings[mappedKey]
imageLabel.Image = image
Oyun Konsolu Haritaları

Yön tuşu kodları, cihaza dayalı herhangi bir farklılığa sahip değildir.Enum.KeyCode.ButtonSelect bazı durumlarda biraz farklı davranır.Kullanıcıların doğru düğmelere göz attığından emin olmak için her iki PlayStation eşleşimini de kullanın.


<th>Oyun Konsolu Geri Dönüş Değeri</th>
<th>Xbox Geri Dönüş Değeri</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.ButtonA</code></td>
<td><code>ButonGeçişi</code></td>
<td><code>DüğmeA</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonB</code></td>
<td><code>ButonYuvarlak</code></td>
<td><code>DüğmeB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td><code>Düğme Kare</code></td>
<td><code>DüğmeX</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonY</code></td>
<td><code>ButonÜçgeni</code></td>
<td><code>DüğmeY</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL1</code></td>
<td><code>DüğmeL1</code></td>
<td><code>DüğmeLB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL2</code></td>
<td><code>DüğmeL2</code></td>
<td><code>DüğmeLT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL3</code></td>
<td><code>DüğmeL3</code></td>
<td><code>DüğmeLS</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR1</code></td>
<td><code>DüğmeR1</code></td>
<td><code>DüğmeRB</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR2</code></td>
<td><code>DüğmeR2</code></td>
<td><code>DüğmeRT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR3</code></td>
<td><code>DüğmeR3</code></td>
<td><code>DüğmeRS</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonStart</code></td>
<td><code>ButonSeçenekleri</code></td>
<td><code>ButonBaşlat</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonSelect</code></td>
<td><code>Dokunmatik Düğme Paneli</code> ve <code>Düğme Paylaşımı</code></td>
<td><code>ButonSeç</code></td>
</tr>
</tbody>
Anahtar Kodu
AnahtarKodlar için Sistem Görüntüleri

Bir görüntü olarak daha iyi temsil edilebilecek bir Enum.KeyCode kullanırken, bir kullanıcı arayüzünde bir ImageLabel için, aşağıdaki miras kalan ikonları kullanabilirsiniz.Ancak, Xbox ve PlayStation kontrolörü simgelerini almak için daha modern ve çok platformlu bir yöntem olarak GetImageForKeyCode() kullanmanız önerilir.


<th>Resim</th>
<th>Varlık Kimliği</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxX.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxX.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonY</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxY.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxY.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonA</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxA.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxA.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonB</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxB.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxB.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadLeft</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadLeft.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/dpadLeft.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadRight</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadRight.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/dpadRight.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadUp</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadUp.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/dpadUp.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.DPadDown</code></td>
<td>
<img src="../../../assets/scripting/controls/dpadDown.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/dpadDown.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonSelect</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxView.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxView.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonStart</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxmenu.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/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>Enum.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>Enum.KeyCode.ButtonL3</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLS.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxLS.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonR3</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRS.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRS.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Thumbstick1</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxLSDirectional.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxLSDirectional.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Thumbstick2</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxRSDirectional.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxRSDirectional.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Backspace</code></td>
<td>
<img src="../../../assets/scripting/controls/backspace.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/backspace.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Return</code></td>
<td>
<img src="../../../assets/scripting/controls/return.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/return.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.LeftShift</code></td>
<td>
<img src="../../../assets/scripting/controls/shift.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/shift.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.RightShift</code></td>
<td>
<img src="../../../assets/scripting/controls/shift.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/shift.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Tab</code></td>
<td>
<img src="../../../assets/scripting/controls/tab.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/tab.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Apostrophe</code></td>
<td>
<img src="../../../assets/scripting/controls/apostrophe.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/apostrophe.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Comma</code></td>
<td>
<img src="../../../assets/scripting/controls/comma.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/comma.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Backquote</code></td>
<td>
<img src="../../../assets/scripting/controls/graveaccent.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/graveaccent.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Period</code></td>
<td>
<img src="../../../assets/scripting/controls/period.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/period.png</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.Space</code></td>
<td>
<img src="../../../assets/scripting/controls/spacebar.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/spacebar.png</code></td>
</tr>
</tbody>
Anahtar Kodu

Parametreler

keyCode: Enum.KeyCode
Varsayılan değer: ""

Dönüşler

GetSupportedGamepadKeyCodes

Bu işlev, verilen Enum.UserInputType ile ilişkili olan bir oyun kolu tarafından desteklenen bir dizi KeyCodes döndürür.

Bu işlev, hangi AnahtarKodların desteklendiğini ve bağlı bir oyun konsolu tarafından desteklenmediğini belirlemek için kullanılabilir.Belirli bir AnahtarKodun desteklendiğini belirlemek için, UserInputService:GamepadSupports() kullanın.

Mevcut olmayan veya bağlı olmayan bir oyun kolu çağrıldığında, bu işlev boş bir dizi döndürecektir.

As UserInputService yalnızca istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadNum: Enum.UserInputType

Oyun kolu Enum.UserInputType 'inin.

Varsayılan değer: ""

Dönüşler

Verilen oyun kolu tarafından desteklenen bir dizi KeyCodes .

Kod Örnekleri

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

Binding Supported Gamepad KeyCodes

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

IsGamepadButtonDown

Bu işlev, belirli bir oyun konsolunda belirli bir düğmeye basılıp basılmadığını kontrol eder.Eğer belirtilen basılmışsa döndürürse, aksi takdirde false döndürür.

Geçerli KullanıcıGirişTürleri

Belirtilen oyun kolu, aşağıdaki KullanıcıGirişTürü sayısal değerlerden biri olmalıdır:


<tr>
<td>Enum.UserInputType.Gamepad1-8'in</td>
</tr>
Adı
Geçerli Anahtar Kodları

Belirtilen düğme, aşağıdaki AnahtarKodları sayısal değerlerinden biri olmalıdır:


<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'a</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadUp</td>
</tr>
<tr>
<td>Enum.KeyCode.DPadDown</td>
</tr>
Adı

Bu, A gibi belirli bir düğmenin basılı tutulup tutulmadığını kontrol etmek için kullanılabilir. Örneğin:


local UserInputService = game:GetService("UserInputService")
local button = Enum.KeyCode.ButtonA
local gamepad = Enum.UserInputType.Gamepad1
local isButtonHeld = UserInputService:IsGamepadButtonDown(gamepad, button)

Çünkü UserInputService sadece istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadNum: Enum.UserInputType

Verilen oyun kolu Enum.UserInputType 'nin.

Varsayılan değer: ""
gamepadKeyCode: Enum.KeyCode

Belirtilen düğmenin Enum.KeyCode 'si.

Varsayılan değer: ""

Dönüşler

Verilen oyun konsolundaki belirtilen oyun düğmesine basılıp basılmadığı.

Kod Örnekleri

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

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

Special Action on Gamepad Button Combo

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

IsKeyDown

Bu işlev, kullanıcının verilen Enum.KeyCode ile ilişkili anahtarı basılı tutup tutmadığını döndürür.Belirtilen anahtar basıldığında true veya basılmadığında false döndürür.

Örneğin, boşluk çubuğu gibi belirli bir anahtarın basılıp basılmadığını kontrol etmek için kullanılabilir. Örneğin:


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

Kullanıcı tarafından basılan tüm anahtarların bir listesini almak için, UserInputService:GetKeysPressed() işlevini kullanın.

Çünkü UserInputService sadece istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

keyCode: Enum.KeyCode

anahtarEnum.KeyCode 'si.

Varsayılan değer: ""

Dönüşler

Belirtilen anahtar basılı tutuluyor mu.

Kod Örnekleri

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

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

Special Action on Key Combo Press

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

IsMouseButtonPressed

Bu işlev bir fare düğmesi alır Enum.UserInputType ve şu anda basılıp basılmadığını gösteren bir bool döndürür.

Kontrol edilen fare düğmesi, işlevin bir argüman olarak geçirdiği Enum.UserInputType değerine bağlıdır. Örneğin:


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

Çünkü UserInputService sadece istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir."

Parametreler

mouseButton: Enum.UserInputType

Fare düğmesinin Enum.UserInputType 'si.

Varsayılan değer: ""

Dönüşler

Verilen fare düğmesi şu anda basılı tutuluyor mu.

Kod Örnekleri

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

IsNavigationGamepad

Bu işlev, belirtilen Enum.UserInputType oyun kolu Navigasyon ve Seçim GuiObjects kontrol etmesine izin verirse true döndürür.

Bir navigasyon oyun kolu ayarlamak istiyorsanız, UserInputService:SetNavigationGamepad() kullanabilirsiniz. Ayrıca tüm navigasyon oyun kollarının bir listesini almak için UserInputService:GetNavigationGamepads() kullanabilirsiniz.

Örneğin, aşağıdaki kod oyun kolu1'in bir navigasyon oyun kolu olup olmadığını kontrol eder:


local UserInputService = game:GetService("UserInputService")
if UserInputService:IsNavigationGamepad(UserInputType.Gamepad1) then
print("Gamepad is a navigation gamepad!")
else
print("Gamepad is not a navigation gamepad!")
end

Navigasyon bağımsız olarak, tüm bağlı oyun konsollarının bir listesi `UserInput/GetConnectedGamepads kullanılarak alınabilir.

Çünkü UserInputService sadece istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadEnum: Enum.UserInputType

Belirtilen oyun kolu Enum.UserInputType 'inin.

Varsayılan değer: ""

Dönüşler

Belirtilen oyun kolu bir navigasyon oyun kolu ise.

RecenterUserHeadCFrame

()

Bu işlev, VR kulaklığın CFrame kafasını kullanıcı tarafından giyilen kulaklığın mevcut yönüne yeniden yerleştirir.Bu, kulaklıkmevcut yönünün CFrame.new() olarak ayarlandığını gösterir.

Bu işlevi kullanarak kulaklık CFrame'ı oyun alanının merkezine taşıyın, eğer garip bir ofsette görünüyorsa.

Bu, VRService işlevine benzer şekilde davranır, VRService:RecenterUserHeadCFrame() .

Çünkü UserInputService sadece istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.


Dönüşler

()

Kod Örnekleri

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

UserInputService:RecenterUserHeadCFrame

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

SetNavigationGamepad

()

SetNavigationGamepad işlevi, belirtilen Enum.UserInputType oyun kolu GUI navigatörünü hareket ettirebilecek mi belirler.GUI navigatörünü hareket ettirmesine izin verilen bir oyun kolu, navigasyon oyun kolu olarak kabul edilir.

etkinleştirildi argümanı olarak geçerse, Gamepad GUI navigatörünü hareket ettirebilir.Argüman false ise, Gamepad GUI navigatörünü hareket ettiremez.

Belirlenmiş bir Oyun Konsolu'nun bir navigasyon konsolu olarak ayarlanıp ayarlanmadığını kontrol etmek istiyorsanız, UserInputService:IsNavigationGamepad() işlevini kullanabilirsiniz.Ayrıca, tüm navigasyon gamepadlerinin bir listesini almak için UserInputService:GetNavigationGamepads() kullanabilirsiniz.

Çünkü UserInputService sadece istemci tarafında olduğundan, bu işlev yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadEnum: Enum.UserInputType

Belirtilen oyun kolu Enum.UserInputType 'inin.

Varsayılan değer: ""
enabled: boolean

Belirtilen oyun kolu GUI navigatörünü hareket ettirebilir mi.

Varsayılan değer: ""

Dönüşler

()

Kod Örnekleri

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

UserInputService:SetNavigationGamepad

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

Etkinlikler

DeviceAccelerationChanged

AygıtHızlandırmaDeğiştirildi etkinliği, bir kullanıcı bir hızlandırıcıya sahip bir cihazı hareket ettirdiğinde ateşlenir.

Bir hızlandırıcı, hızlanmayı ölçen çoğu mobil cihazda bulunan bir bileşendir (hız değişimi).

Bir kullanıcının cihazının bir hızlandırıcıya sahip olup olmadığını belirlemek için, bakın UserInputService.AccelerometerEnabled .

Bu etkinlik, hızlandırıcıya sahip bir cihazın hareketini izlemek için kullanılabilir.Örnek kullanım, mobil bir cihaz hızlandığında oyuncu karakterini hareket ettirmeyi içerir.

Ayrıca, bu etkinin UserInputService:GetDeviceAcceleration() ile birlikte kullanılması, bir cihazın hızlandırıcıya sahip olması durumunda kullanıcının mevcut hareketini belirlemek için kullanılabilir.

Bu etkinlik yalnızca yerel olarak ateşlenir - bu da sadece cihazı hareket eden oyuncunun etkinliği kullanabileceği ve sadece bir LocalScript içinde çalışacağı anlamına gelir.

Parametreler

acceleration: InputObject

Bir InputObject , bir UserInputType ile, ve her yerel cihaz ekseninde yerçekiminin gücünü gösteren 'Accelerometer' , ve Position , her bir yerçekiminin gücünü gösteren.


Kod Örnekleri

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

Control Players Using the Accelerometer

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

DeviceGravityChanged

The UserInputService.DeviceGravityChanged etkinliği, bir hızlandırıcıya sahip bir cihazda cihazın yerçekimi Vector3 değiştiğinde ateşlenir.

Bir cihazın yerçekimi vektörü, cihazın X, Y ve Z eksenlerindeki yerçekim gücünü temsil eder.Yerçekimi asla değişmezken, her bir eksene uyguladığı kuvvet, cihaz döndüğünde ve yön değiştirdiğinde değişir.Her eksene uygulanan güç değeri -1'den 1'e kadar değişen bir birim vektörüdür.

Bir hızlandırıcı, hızlanmayı ölçen çoğu mobil cihazda bulunan bir bileşendir (hız değişimi).

Bu etkinlik, bir kullanıcının cihazındaki yerçekimi gücünün gerçek dünya yönünü belirlemek için kullanılabilir.Bu daha sonra oyun içinde bir kullanıcının cihazındaki yerçekimi gücünü simüle etmek için kullanılabilir, örneğin oyun içi nesnelerde (aşağıdaki örnek bakın).

Bir kullanıcının cihazının hızlandırıcıya sahip olup olmadığını kontrol etmek için, bakın UserInputService.AccelerometerEnabled .Cihazda bir hızlandırıcı etkinleştirildiyse, kullanıcının cihazındaki mevcut yerçekimi gücünü almak için UserInputService:GetDeviceGravity() işlevini kullanabilirsiniz.

Parametreler

gravity: InputObject

Her yerel cihaz ekseninde yerçekiminin gücünü gösteren bir InputObject , InputObject.Position özelliği ileBu pozisyon, cihazla ilgili yerçekimi yönünü belirlemek için bir yön olarak kullanılabilir.


Kod Örnekleri

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

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

Move a Ball using the Accelerometer

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

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

DeviceRotationChanged

CihazDöndürmeDeğiştirildi etkinliği, bir kullanıcı jiroskopu olan bir cihazı döndürdüğünde ateşlenir.

Bir jiroskop, yön ve dönme hızını algılayan çoğu mobil cihazda bulunan bir bileşendir.

Etkinlik, cihazın yönünü ve kullanıcının cihazı döndürdüğünde değişiklikleri izlerken yararlıdır.Mevcut cihaz dönüşünü belirlemek için, UserInputService:GetDeviceRotation() fonksiyonunu kullanabilirsiniz.

Bir kullanıcının cihazının bir jiroskopu var olup olmadığını ve bu olayın ateşleneceğini kontrol etmek için, bakın UserInputService.GyroscopeEnabled .

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Parametreler

rotation: InputObject

Bir InputObject cihazın dönüşü hakkında bilgi sağlayan.InputObject.Position yeni dönüşü bir Vector3 pozisyonel değeri ve InputObject.Delta dönüşteki değişimi bir Vector3 pozisyonel değerde temsil eder.

cframe: CFrame

cihazmevcut yönünü temsil eden bir CFrame .


Kod Örnekleri

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

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


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

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

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

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

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

Create a Gyroscopic Camera

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

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

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

Move a Ball using the Accelerometer

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

GamepadConnected

Oyun Konsolu Bağlı etkinliği, bir oyun konsolu istemciye bağlandığında ateşlenir.

Bir Roblox oyunu çok sayıda kontrolörü desteklediğinden, bu etkinlik aktif olan kontrolörler/oyun pedlerini izlemek için UserInputService.GamepadDisconnected etkinliği ile eşleştirildiğinde yararlıdır.Ayrıca kullanmak için doğru oyun kolu bulmak için UserInputService:GetConnectedGamepads() kullanabilirsiniz.

Aşağıdaki örnek, bir oyun kolu kliente bağlandığında izlemenin bir kullanım örneğini gösterir.


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

Hangi cihazların bağlı olduğunu görmek istiyorsanız, UserInputService:GetConnectedGamepads() fonksiyonunu kullanabilirsiniz.

Bu olay yerel olarak ateş olduğundan, sadece bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadNum: Enum.UserInputType

Bağlı oyun konsolunun Enum.UserInputType 'si.


GamepadDisconnected

Oyun kolu bağlantısı kesildi etkinliği, bir oyun kolu bağlantısı kesildiğinde ateş edilir.

Bir Roblox oyunu çok sayıda kontrolörü desteklediğinden, bu etkinlik aktif olan kontrolörler/oyun pedlerini izlemek için UserInputService.GamepadConnected etkinliği ile eşleştirildiğinde yararlıdır.Ayrıca kullanmak için doğru oyun kolu bulmak için UserInputService:GetConnectedGamepads() kullanabilirsiniz.

Aşağıdaki örnek, bir oyun kolu kullanımdan koparıldığında bir izlemenin kullanım örneğini gösterir.


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

Bu olay yerel olarak ateş olduğundan, sadece bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

gamepadNum: Enum.UserInputType

Bağlantı kesilmiş oyun kolu Enum.UserInputType 'inin.


InputBegan

InputBegan etkinliği, bir kullanıcının bir İnsan-Bilgisayar Arayüzü cihazı aracılığıyla etkileşime başladığında ateşlenir (fare düğmesü aşağı, dokunma başlar, klavye düğmesi aşağı, vb.).

Kullanıcı etkileşiminin başlangıcını izlemek için kullanılabilir, örneğin bir kullanıcı ilk önce bir GUI öğesi, oyun konsolu vb. ile etkileşime girer.Fare tekerleği hareketlerini yakalamaz.

Bu etkinlik, kullanıcı girişinin, değişikliklerin ve bitişinin ne zaman başladığını izlemek için UserInputService.InputChanged ve UserInputService.InputEnded ile birlikte kullanılabilir.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Parametreler

Kullanıcının girişiyle ilgili bilgileri içeren bir InputObject durum.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

Handling InputBegan

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

InputChanged

Giriş Değiştirildi etkinliği, bir kullanıcının bir İnsan-Bilgisayar Arayüzü cihazı aracılığıyla nasıl etkileşime girdiğini değiştirdiğinde ateşlenir (fare tuşu aşağı, dokunma başlangıcı, klavye tuşu aşağı vb.).

Roblox tarafından otomatik olarak işlenen olayları görmezden gelmek için, ScrollingFrame kaydırma gibi, oyunİşlenmişOlay argümanının yanlış olduğunu kontrol edin.Bu etkinlik, UserInputService.InputBegan ve UserInputService.InputEnded ile birlikte kullanılarak kullanıcı girişinin, değişikliklerin ve bitişinin ne zaman başladığını izleyebilir.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Parametreler

Kullanıcının girişiyle ilgili bilgileri içeren bir InputObject durum.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

Handling InputChanged

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

InputEnded

GirişBitti etkinliği, bir kullanıcının İnsan-Bilgisayar Arayüzü cihazı üzerinden etkileşimini durdurduğunda ateşlenir (fare düğmesi aşağı, dokunma başlar, klavye düğmesi aşağı, vb.).Bir kullanıcı bir klavye anahtar, fare düğmesi, dokunma ekranı girişi vb. serbest bıraktığını izlerken bu yararlıdır.

Bu etkinlik, kullanıcı girişinin, değişikliklerin ve bitişinin ne zaman başladığını izlemek için UserInputService.InputBegan ve UserInputService.InputChanged ile birlikte kullanılabilir.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Parametreler

Kullanıcı girişiyle ilgili bilgileri içeren bir InputObject durum,

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

Handling InputEnded

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

JumpRequest

JumpRequest etkinliği, istemci tarafından bir atlama isteği olduğunda çalışır, örneğin istemci mobil cihazda boşluk tuşuna veya atlama düğmesine bastığında. UserInputService

Bu olay, kullanıcının Player.Character zıplamayapmaya çalıştığında herhangi bir zamanda ateşlenir.Varsayılan davranış, oyuncunun Humanoid.Jump özelliğini doğru olarak ayarlayarak bir atlama isteğine yanıt verir, bu da oyuncunun karakterinin zıplamasağlar.

Etkinlik, bir oyuncunun zıplamaistediği her seferi izlemek için kullanılabilir.Bir oyuncunun zıplamayapmak için kullanmak yerine, varsayılan atlama davranışını değiştirmek için kullanılmalıdır - örneğin atlamayı devre dışı bırakmak.

Örneğin, aşağıdaki kod, oyuncu bir atlama talepgönderdiğinde her seferinde "Zıplama" yazdırır.


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

Bu olay, tek bir talepisteği için birden fazla kez ateş olduğundan, bir gecikme kullanılması önerilir.

Anahtarları veya düğmeleri diğer eylemlere bağlamak istiyorsanız, UserInputService:GetKeysPressed() ve UserInputService.InputBegan veya ContextActionService gibi olayları kullanmayı düşünün.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.


Kod Örnekleri

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

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

Disable Jumping

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

LastInputTypeChanged

etkinliği, müşterinin bir İnsan-Bilgisayar Arayüzü cihazı aracılığıyla nasıl etkileşime girdiğini değiştirdiğinde her zaman ateşlenir.(i.e.MouseMovement'ten MouseWheel'e veya Thumbstick1'den Thumbstick2'ye).

Değişip değişmediğine bakılmaksızın, son giriş yazdeğerini almak için UserInputService:GetLastInputType() işlevini kullanabilirsiniz.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Parametreler

lastInputType: Enum.UserInputType

Son giriş yazgösteren bir Enum.UserInputType .


Kod Örnekleri

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

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

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

Hide Mouse During Keyboard Input

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

PointerAction

İşaret Etme Eylemi , kullanıcı belirli bir işaret etme aksiyongerçekleştirdiğinde ateş eder. Özellikle, fare tekerleğini kaydırma.

Parametreler

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

TextBoxFocusReleased

etkinliği, bir müşterinin bir üzerinde odaklanmasını kaybettiğinde ateşlenir, genellikle bir müşterinin dönüş tuşuna basarak veya ekranda başka bir yere tıklayarak metin girişini durdurduğunda.

Örneğin, aşağıdaki kod, olay ateşlendiğinde odak kaybına uğrayan TextBox adını yazdırır.


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

Bir TextBox kazanır ve kaybeder odaklandığını izlemek için UserInputService.TextBoxFocused yanında kullanılabilir.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın

Parametreler

textboxReleased: TextBox

Odak kaybeden TextBox .


TextBoxFocused

Bu olay, bir kazanç odaklanırken bir TextBox üzerinde ateşlenir, genellikle bir müşteri metin girişine başlamak için bir metin kutusuna tıklar/dokunur.Ayrıca, bir metin kutusu odaklanması TextBox:CaptureFocus() kullanılarak odaklanırsa da ateş edilir.

Örneğin, aşağıdaki kod, olay ateşlendiğinde odaklanan TextBox adını yazdırır.


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

Bir metin kutusunun odak kazandığı ve kaybettiği zamanı izlemek için UserInputService.FocusReleased ile birlikte kullanılabilir.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın

Parametreler

textboxFocused: TextBox

Odak kazanan TextBox .


TouchDrag

Parametreler

dragDirection: Enum.SwipeDirection
numberOfTouches: number
gameProcessedEvent: boolean

TouchEnded

Dokunma Bitti etkinliği, bir kullanıcı dokunma girişini bir Dokunma Etkinleştirilmiş cihazın ekranından serbest bıraktığında ateşlenir ve cihazla dokunma girişini bitirir.

Bu etkinlik, bir kullanıcının cihazının ekranına dokunmayı bıraktığını belirlemek için kullanılabilir.Bir kullanıcının ekrana dokunmaya başladığı ve durduğu anı belirlemek için UserInputService.TouchStarted ile eşleştirilebilir.

Örneğin, aşağıdaki kod, kullanıcının ekrana dokunmayı bıraktığı ekran konumunu basar.


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

Dokunma giriş nesnesi, dokunma süresi boyunca aynı giriş nesnesidir.Bu nedenle dokunma nesneleri olduklarında InputObjects karşılaştırması aynı parmak olup olmadığını belirlemek için geçerlidir.

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

Kullanıcının girişiyle ilgili bilgileri içeren bir InputObject durum.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

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

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

The Difference Between TouchTap and TouchLongPress

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

TouchLongPress

Bir kullanıcı, bir dokunma etkinleştirilmiş cihazın aynı ekran konumunda kısa bir süre için en az bir parmağı tutarken ateş edilir.

Bu etkinlik, bir kullanıcının bir oyundaki GuiObject veya bir eleman üzerinde parmağını ne zaman tuttuğunu belirlemek için kullanılabilir.

Aşağıdaki örnek, kullanıcının aynı ekran pozisyonunda kısa bir süre için en az bir parmağı tutarken uzun basmanın state'sini yazdırır.Olası durumlar şunları içerir: Başla , Değiştir , Sonlandır , İptal et ve Hiçbiri.


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)

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bir kullanıcının ekrana dokunmaya başladığı ve durduğu anı belirlemek için UserInputService.TouchStarted ve UserInputService.TouchEnded ile eşleştirilebilir.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

touchPositions: Array

Harekete dahil olan parmakların konumunu gösteren bir dizi Vector2 nesne, işaret eden bir dizi.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

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

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

The Difference Between TouchTap and TouchLongPress

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

TouchMoved

Bir kullanıcı parmağını bir TouchEnabled tablet veya akıllı telefon gibi bir cihaz üzerinde hareket ettirdiğinde ateş eder.

Bu etkinlik, bir kullanıcının ekranda parmağını hareket ettirdiğini ve parmağını nereye hareket ettirdiğini izlemek için yararlıdır.

Aşağıdaki kod, dokunmanın önceki konumundan yeni bir pozisyona TouchEnabled bir cihazda hareket ettiğini gösterir.Geçen InputObject.Position çözümleme parametresindeki touch nın bir Vector3 olduğunu unutmayın, ancak sadece X ve Y koordinatlarını içerir; Z daima 0'dur.


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)

Bir kullanıcı ekrana dokunmaya başladığında, dokunurken parmaklarının hareket ettiği süre ve ekrana dokunmayı bıraktığı süre belirlemek için bu olayı UserInputService.TouchStarted ve UserInputService.TouchEnded ile eşleştirin.

Bir kullanıcının cihazının dokunmayı desteklediğini ve dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

Kullanıcının girişiyle ilgili bilgileri içeren bir InputObject durum.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

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

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

The Difference Between TouchTap and TouchLongPress

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

TouchPan

TouchPan etkinliği, bir kullanıcı en az bir parmağı bir TouchEnabled cihazına sürüklediğinde ateşlenir.

Bu etkinlik, bir kullanıcının bir dokunma etkinleştirilmiş cihazın ekranında parmağını döndürdüğü zamanı belirlemek için kullanılabilir - örneğin, özel bir kamera senaryosunda Camera döndürmek.

Aşağıdaki kısım "Dokunma hızı sürükleme" basılır ve kullanıcı parmağını ekrana sürdüğünde kullanıcının dokunma hızı takip edilir.


local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
print("Speed of touch drag: " .. tostring(velocity))
end)

Başka yararlı UserInputService işlevine burada bir göz atın UserInputService.TouchRotate .

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

touchPositions: Array

Dokunma konumlarını (örneğin parmaklar) işaret eden bir dizi Vector2 nesne, harekete dahil olan dokunma nesneleri.

totalTranslation: Vector2

Tencere hareketinin başından sonuna kadar boyutu (piksel olarak).

velocity: Vector2

Tava hareketinin hızı (piksel başına saniye) saniye başına.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

TouchPinch

Bir kullanıcı bir TouchEnabled cihazın ekranına iki parmak yerleştirdiğinde ve hareket ettirdiğinde ateş edilir.

durum, aşağıdaki kısım, dokunma çekiminin başlangıcından bu yana kameranın yakınlaştırma ölçeğinin ne kadar değiştiğini basar.


local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPinch:Connect(function(touchPositions, scale, velocity, state, gameProcessedEvent)
print("Scale difference since beginning of pinch: " .. tostring(scale))
end)

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir.Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

touchPositions: Array

Kıskaç hareketine dahil olan parmakların ekran konumunu gösteren bir Vector2s dizi, pikselde, parmakların kıskaç hareketine dahil olduğunu gösteren bir dizi.

scale: number

Başlangıçtan bitişe olan sıkışma büyüklüğü (piksellere bölünerek) başlangıç sıkışma konumları tarafından bölünür.

velocity: number

Dokunma hareketinin hızı (piksel başına saniye) saniye başına.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

TouchRotate

Dokunma Döndürme etkinliği, bir kullanıcının bir TouchEnabled cihazda iki parmağı döndürdüğünde ateşlenir.

Örneğin, aşağıdaki kod, dokunma dönüşünden bu yana kameranın ne kadar döndüğünü basar.


local UserInputService = game:GetService("UserInputService")
UserInputService.TouchRotate:Connect(function(touchPositions, rotation, velocity, state, gameProcessedEvent)
print("Camera has rotated " .. tostring(rotation) .. " degrees!")
end)

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Bir mobil cihazda kullanıcının kamerasını kontrol eden temel kodlar bu olayla benzer şekilde çalışan kodu kullanır.Bu etkinlik için en iyi uygulama, varsayılan temel senaryoları geçmek için bir mobil kamera sistemi oluştururken kullanmaktır.

Ayrıca bakın:

Parametreler

touchPositions: Array

Harekete dahil olan parmakların konumlarını gösteren bir Vector2s dizi, işaretleyici.

rotation: number

Hareketin başlangıcından bu yana döndürdüğü derece sayısı.

velocity: number

Döndürme değişikliği (derecelerle) değişikliğin süresine bölünerek (saniyelerle).

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

The script is broken into two parts:

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

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

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

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

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

Create a Custom CameraScript

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

TouchStarted

Dokunma Başlatma etkinliği, bir kullanıcı parmağını bir TouchEnabled cihazın üzerine yerleştirdiğinde ateşlenir ve cihazla dokunma girişi başlar.

Bu etkinlik, bir kullanıcının cihazın ekranına dokunmaya başladığı zamanı belirlemek için kullanılabilir.Bir kullanıcının ekrana dokunmaya başladığı ve durduğu anı belirlemek için UserInputService.TouchEnded ile eşleştirilebilir.

Dokunma giriş nesnesi, dokunma süresi boyunca aynı giriş nesnesidir.Bu nedenle dokunma nesneleri olduklarında InputObjects karşılaştırması aynı parmak olup olmadığını belirlemek için geçerlidir.

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

Kullanıcının girişiyle ilgili bilgileri içeren bir InputObject durum.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

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

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

Tracking Touches

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

TouchSwipe

etkinliği, bir kullanıcı parmaklarını bir cihazda kaydettiğinde ateşlenir.

Bu etkinlik, bir kullanıcının cihazının ekranında parmaklarını kaydırdığı zamanı ve kullanıcının kaydettiği yönü belirlemek için kullanılabilir.

Dokunma giriş hareketinin daha kesin takibi için, UserInputService.TouchMoved kullanın

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

swipeDirection: Enum.SwipeDirection

Bir Enum.SwipeDirection , kullanıcının kaydettiği yönü gösteren.

numberOfTouches: number

Harekete dahil edilen dokunma sayısı (örneğin parmaklar).

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

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

Touch Swipe a GUI

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

TouchTap

Dokunma etkinliği, kullanıcının ekranda bir TouchEnabled cihazda parmak dokundurduğunda ateşlenir.

Bu olay, kullanıcının oyun dünyasına dokunup/dokunmadığına bakmaksızın ateşlenecektir. GuiObject bir element.Kullanıcı sadece oyun dünyasına dokunduğunda veya dokunduğunda ateşlenen bir etkinlik arıyorsanız, UserInputService.TouchTapInWorld kullanın.

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.

Parametreler

touchPositions: Array

Dokunma hareketine dahil olan parmakların konumunu gösteren bir dizi Vector2 nesne, objeleri.

gameProcessedEvent: boolean

Oyun motorunun bu girişi içeriden gözlemlediğini ve buna göre hareket ettiğini gösterir.Genellikle bu, UI işlemiyle ilgilidir, bu nedenle bir düğme bu girişten dokunuldu veya tıklandıysa, gameProcessedEvent olurdu true.Bu ayrıca ContextActionService üzerinden bağlanan giriş olayları için de geçerlidir.


Kod Örnekleri

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

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

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

The Difference Between TouchTap and TouchLongPress

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

TouchTapInWorld

TouchTapInWorld etkinliği, kullanıcının ekranda bir TouchEnabled cihazda parmak dokunduğunda ateşlenir.Kullanıcı oyun dünyasına dokunduğunda ateşlenir.

Bu etkinlik, bir kullanıcının ekrana dokunduğu ve bir GuiObject elemanına dokunmadığı zamanı belirlemek için kullanılabilir.Kullanıcı bir GUI öğesine dokunursa, UserInputService.TouchTap TouchTapInWorld yerine ateş edecektir.

Bir kullanıcının cihazının TouchEnabled olup olmadığını ve bu dokunma olaylarının ateşleneceğini kontrol etmek için, UserInputService.TouchEnabled görün.

Bu etkinlik yalnızca Roblox istemci penceresi odakta olduğunda ateşlenir. Örneğin, pencere azaltıldığında girişler yakalanmayacaktır.

Sadece yerel olarak ateş olduğundan, sadece bir LocalScript içinde kullanılabilir.

Ayrıca bakın:

Parametreler

position: Vector2

Dokunma konumunu gösteren bir Vector2 .

processedByUI: boolean

Kullanıcı bir GUI öğesine dokunduysa.


Kod Örnekleri

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

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

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

Create a Part in World at Touch Position

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

WindowFocusReleased

The UserInputService WindowFocusReleased etkinliği, Roblox istemcisinin penceresinin odak kaybettiğinde ateşlenir - genellikle Roblox istemcisi kullanıcı tarafından azaltıldığında.

Örneğin, aşağıdaki kod Roblox istemcisi odak kaybettiğinde her zaman “Pencere odaklandırma serbest bırakıldı” yazdırır.


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

Bu etkinlik, Roblox istemcisinin bir kullanıcının ekranına aktif olarak odaklandığını izlemek için UserInputService.WindowFocused ile birlikte kullanılabilir.

Yalnızca yerel olarak ateş olduğundan, sadece bir LocalScript içinde kullanılabilir.


Kod Örnekleri

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

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

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

Window Focus AFK Script (Script)

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

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

Window Focus AFK Script (LocalScript)

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

WindowFocused

The UserInputService WindowFocused etkinliği, Roblox istemcisinin penceresinin odaklanması sırasında ateşlenir - tipik olarak Roblox istemcisi kullanıcının ekranında maksimuma ulaşır/aktif olarak açılır.

Örneğin, aşağıdaki kod herhangi bir Roblox istemcisi odaklanırken “Pencere odaklı” her zaman yazdırır.


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

Bu etkinlik, Roblox istemcisinin bir kullanıcının ekranına aktif olarak odaklandığını izlemek için UserInputService.WindowFocusReleased ile birlikte kullanılabilir.

Bu olay yalnızca yerel olarak ateş olduğundan, yalnızca bir LocalScript içinde kullanılabilir.


Kod Örnekleri

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

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

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

Window Focus AFK Script (Script)

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

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

Window Focus AFK Script (LocalScript)

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