UserInputService
*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.
UserInputService é um serviço usado para detectar e capturar os diferentes tipos de entrada disponíveis no dispositivo de um usuário.
O propósito principal deste serviço é permitir que as experiências cooperem com várias formas de entrada disponíveis, como gamepads, telas de toque e teclados.Permite que um LocalScript execute diferentes ações dependendo do dispositivo e, por sua vez, forneça a melhor experiência para o usuário final.
Alguns usos deste serviço incluem detectar a entrada do usuário quando eles interagem com GUIs, ferramentas e outras instâncias de jogo.Para detectar a entrada do usuário, o serviço deve procurar um evento de serviço.Por exemplo, o serviço pode detectar eventos como quando o usuário toca na tela de um dispositivo móvel usando UserInputService.TouchStarted , ou conecta um gamepad, como um controlador Xbox, ao seu dispositivo usando UserInputService.GamepadConnected .
Como este serviço é apenas do lado do cliente, ele só funcionará quando usado em um LocalScript ou um ModuleScript necessário por um LocalScript .Como o UserInputService é apenas do lado do cliente, os usuários no jogo só podem detectar sua própria entrada - e não a entrada de outros.
Veja também ContextActionService , um serviço que permite vincular funções a várias entradas de usuário.
Amostras de código
The following example demonstrates one of many usage examples of handling a UserInputService event.
-- We must get the UserInputService before we can use it
local UserInputService = game:GetService("UserInputService")
-- A sample function providing one usage of InputBegan
local function onInputBegan(input, _gameProcessed)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed!")
end
end
UserInputService.InputBegan:Connect(onInputBegan)
Resumo
Propriedades
Descreve se o dispositivo do usuário tem um acelerômetro.
Descreve se o dispositivo usado por um usuário tem um controle / controle de jogodisponível.
Descreve se o dispositivo do usuário tem um giroscópio.
Descreve se o dispositivo do usuário tem um teclado disponível.
Determina se o mouse do usuário pode ser movido livremente ou está bloqueado.
Escala a saída delta (mudança) do usuário de Mouse.
Descreve se o dispositivo do usuário tem um mouse disponível.
O ID do conteúdo da imagem usada como ícone do mouse do usuário.
Determina se o ícone Mouse é visível.
Determina a posição do teclado na tela.
Determina o tamanho do teclado na tela.
Descreve se um teclado na tela está atualmente visível na tela do usuário.
Descreve se o dispositivo atual do usuário tem um touch-screen disponível.
Indica se o usuário está usando um óculosde realidade virtual.
Métodos
Retorna se o gamepad dado Enum.UserInputType suporta um botão correspondente ao dado Enum.KeyCode.
Retorna um array de Enum.UserInputType gamepads atualmente conectados.
Retorna um InputObject que descreve a aceleração atual do dispositivo.
Retorna um InputObject descrevendo o vetorde gravidade atual do dispositivo.
Retorna um InputObject e um CFrame, descrevendo o vetor de rotação atual do dispositivo.
Retorna o atualmente TextBox o cliente está atualmente focado.
Retorna se um gamepad com o dado Enum.UserInputType ''gamepadNum'' está conectado.
Retorna um array de InputObjects para todos os inputs disponíveis no controle / controle de jogodado, representando o último estado de entrada de cada input.
Retorna uma imagem para o solicitado Enum.KeyCode .
Retorna um array de InputObjects associado ao keys atualmente sendo pressionado para baixo.
Retorna o Enum.UserInputType associado ao mais recente input do usuário.
Retorna um array de InputObjects correspondendo aos botões do mouse que estão sendo mantidos pressionados atualmente.
Retorna a mudança, em pixels, da posição do Mouse do jogador na última imagem renderizada. Funciona apenas se o mouse estiver bloqueado.
Retorna a localização da tela atual do jogador de Mouse em relação ao canto superior esquerdo da tela.
Retorna um array de gamepads conectados e habilitados para navegação GUI em ordem decrescente de prioridade.
Retorna uma string que representa uma tecla que o usuário deve pressionar para inserir um dado Enum.KeyCode .
Retorna um array de KeyCodes que o gamepad associado ao dado Enum.UserInputType suporta.
Determina se um botão específico é pressionado em um controle / controle de jogoespecífico.
Retorna se o dado key atualmente está pressionado.
Retorna se o dado mouse button atualmente está pressionado.
Retorna verdadeiro se o gamepad especificado Enum.UserInputType for permitido controlar a navegação GuiObjects.
Recentra o CFrame da fone de ouvido VR para a orientação atual do fone de ouvido usado pelo usuário.
Define se o especificado Gamepad pode ou não mover o navegador GuiObject.
Eventos
Dispedido quando um usuário move um dispositivo que tem um acelerômetro. Usado para rastrear o movimento de dispositivos do mundo real dentro de um jogo do Roblox.
Dispedido quando a força da gravidade muda em um dispositivo que tem um acelerômetro ativado - como um dispositivo móvel.
Dispedido quando um usuário gira um dispositivo que tem um giroscópio.
Dispara quando um gamepad é conectado ao cliente. Passa o "gamepadNum" do gamepad que foi conectado.
Dispara quando um gamepad é desconectado do cliente. Passa o Enum.UserInputType do gamepad que foi desconectado.
Dispedido quando um usuário começa a interagir através de um dispositivo de Interface Humano-Computador - como um mouse ou controle / controle de jogo.
Dispedido quando um usuário muda como está interagindo através de um dispositivo de Interface Humano-Computador.
Incêndios quando um usuário para de interagir através de um dispositivo de Interface Humano-Computador.
Incêndios sempre que o cliente faz um pedido para que seu personagem pular.
Dispara quando o Enum.UserInputType do cliente é alterado.
- PointerAction(wheel : number,pan : Vector2,pinch : number,gameProcessedEvent : boolean):RBXScriptSignal
Incêndios quando o usuário executa uma ação de ponteiro específica (roda, pinça, girar).
Dispedido quando o cliente perde o foco em um TextBox .
Dispedido quando o cliente se concentra em um TextBox.
- TouchDrag(dragDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Dispedido quando um usuário solta seu dedo da tela em um dispositivo TouchEnabled - como a tela de um dispositivo móvel.
- TouchLongPress(touchPositions : Array,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Dispedido quando um usuário mantém pelo menos um dedo por um curto período de tempo na mesma posição na tela em um dispositivo TouchEnabled - como a tela de um dispositivo móvel.
Dispara quando um usuário move o dedo em um dispositivo TouchEnabled , como um tablet ou smartphone.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Dispedido quando um usuário arrasta pelo menos um dedo em um dispositivo TouchEnabled - como a tela de um dispositivo móvel.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Disparado quando um usuário morde seus dedos em um dispositivo TouchEnabled - como a tela de um dispositivo móvel.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
Dispara quando um usuário gira dois dedos em um dispositivo TouchEnabled - como a tela de um dispositivo móvel.
Disparado quando um usuário coloca o dedo em um dispositivo habilitado para toque - como a tela de um iPad ou iPhone da Apple ou um telefone Android do Google.
- TouchSwipe(swipeDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
Incêndios em um dispositivo TouchEnabled quando um usuário coloca seu(s) dedo(s) na tela, passa pela tela e levanta seu dedo com uma certa velocidade de movimento.
Dispedido quando um usuário toca seu dedo em um dispositivo TouchEnabled - como a tela de um dispositivo móvel.
Dispara quando um usuário toca o mundo do jogo em um dispositivo TouchEnabled - como a tela de um dispositivo móvel.
Incêndios quando a janela do cliente Roblox perde o foco na tela do usuário.
Incêndios quando a janela do cliente Roblox ganha foco na tela do usuário.
Propriedades
AccelerometerEnabled
Essa propriedade descreve se o dispositivo do usuário tem um acelerômetro
Um acelerômetro é um componente encontrado na maioria dos dispositivos móveis que mede aceleração (mudança na velocidade).
Por exemplo, o seguinte trecho de código mostra como verificar se o dispositivo do usuário tem um acelerômetro.
local UserInputService = game:GetService("UserInputService")local accelerometerEnabled = UserInputService.AccelerometerEnabledif accelerometerEnabled thenprint("Accelerometer enabled!")elseprint("Accelerometer not enabled!")end
Se o dispositivo tiver um acelerômetro ativado, você pode obter sua aceleração atual usando a função UserInputService:GetDeviceAcceleration() ou rastrear quando a aceleração do dispositivo muda usando o evento UserInputService.DeviceAccelerationChanged.
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Amostras de código
This code adds a force on a part so that it falls in the direction of actual gravity relative to the user's device.
In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have an accelerometer.
local Workspace = game:GetService("Workspace")
local UserInputService = game:GetService("UserInputService")
local ball = script.Parent:WaitForChild("Ball")
local mass = ball:GetMass()
local gravityForce = ball:WaitForChild("GravityForce")
local function moveBall(gravity)
gravityForce.Force = gravity.Position * Workspace.Gravity * mass
end
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceGravityChanged:Connect(moveBall)
end
This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.
The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:
camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *currentRotation
The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.
The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.
Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.
In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_rotation, rotCFrame)
if orientationSet then
if not lastInputFrame then
lastInputFrame = rotCFrame
end
local delta = rotCFrame * lastInputFrame:inverse()
local x, y, z = delta:ToEulerAnglesXYZ()
if upsideDown then
delta = CFrame.Angles(-x, y, z)
else
delta = CFrame.Angles(x, -y, z)
end
currentRotation = currentRotation * delta
lastInputFrame = rotCFrame
end
end
local function HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end
GamepadEnabled
Essa propriedade descreve se o dispositivo usado por um usuário tem um controle / controle de jogodisponível.Se os gamepads estiverem disponíveis, você pode usar UserInputService:GetConnectedGamepads() para recuperar uma lista de gamepads conectados.
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Veja também:
Amostras de código
If you are using the default controls, you do not need to worry about this. If you're creating a custom script for handling gamepad controls, this is a good template for retrieving which gamepad enum you should use as the primary gamepad controller.
local UserInputService = game:GetService("UserInputService")
local function getActiveGamepad()
local activeGamepad = nil
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for _, gamepad in connectedGamepads do
if activeGamepad == nil or gamepad.Value < activeGamepad.Value then
activeGamepad = gamepad
end
end
end
if activeGamepad == nil then -- Nothing is connected; set up for "Gamepad1"
activeGamepad = Enum.UserInputType.Gamepad1
end
return activeGamepad
end
if UserInputService.GamepadEnabled then
local activeGamepad = getActiveGamepad()
print(activeGamepad)
end
GyroscopeEnabled
Essa propriedade descreve se o dispositivo do usuário tem um giroscópio.
Um giroscópio é um componente encontrado na maioria dos dispositivos móveis que detecta orientação e velocidade de rotação.
Se o dispositivo de um usuário tiver um giroscópio, você pode incorporá-lo ao seu jogo usando a função UserInputService:GetDeviceRotation() e o evento UserInputService.DeviceRotationChanged.
local UserInputService = game:GetService("UserInputService")local gyroIsEnabled = UserInputService.GyroscopeEnabledif gyroIsEnabled thenprint("Gyroscope is enabled!")elseprint("Gyroscope is not enabled!")end
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Amostras de código
This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.
The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:
camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *currentRotation
The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.
The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.
Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.
In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_rotation, rotCFrame)
if orientationSet then
if not lastInputFrame then
lastInputFrame = rotCFrame
end
local delta = rotCFrame * lastInputFrame:inverse()
local x, y, z = delta:ToEulerAnglesXYZ()
if upsideDown then
delta = CFrame.Angles(-x, y, z)
else
delta = CFrame.Angles(x, -y, z)
end
currentRotation = currentRotation * delta
lastInputFrame = rotCFrame
end
end
local function HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end
KeyboardEnabled
Essa propriedade descreve se o dispositivo do usuário tem um teclado disponível.Esta propriedade é true quando o dispositivo do usuário tem um teclado disponível, e false quando não o faz.
Pode ser usado para determinar se o usuário tem um teclado disponível - que pode ser importante se você quiser verificar se pode usar UserInputService:IsKeyDown() ou UserInputService:GetKeysPressed() para verificar a entrada do teclado.
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Amostras de código
This example prints "The user's device has an available keyboard!" if KeyboardEnabled is true and "The user's device does not have an available keyboard!" if KeyboardEnabled is false.
local UserInputService = game:GetService("UserInputService")
if UserInputService.KeyboardEnabled then
print("The user's device has an available keyboard!")
else
print("The user's device does not have an available keyboard!")
end
MouseBehavior
Essa propriedade define como o mouse do usuário se comporta com base no enum Enum.MouseBehavior. Pode ser definida para três valores:
- Enum.MouseBehavior.Default — O mouse se move livremente ao redor da tela do usuário.
- Enum.MouseBehavior.LockCenter — O mouse está bloqueado e não pode se mover do centro da tela do usuário.
- Enum.MouseBehavior.LockCurrentPosition — O mouse está bloqueado e não pode se mover de sua posição atual na tela do usuário no momento do bloqueio.
O valor desta propriedade não afeta a sensibilidade do rastreamento de eventos ao movimento do mouse.Por exemplo, GetMouseDelta retorna a mesma posição na tela Vector2 em pixels, independentemente de se o mouse está bloqueado ou pode se mover livremente ao redor da tela do usuário.Como resultado, scripts padrão como os que controlam a câmera não são afetados por essa propriedade.
Essa propriedade é substituída se um GuiButton com Modal habilitado for GuiButton.Visible se o botão direito do jogador estiver para baixo.
Observe que, se o mouse estiver bloqueado, UserInputService.InputChanged ainda disparará quando o jogador mover o mouse e passará pelo Delta que o mouse tentou mover.Além disso, se o jogador for expulso do jogo, o mouse será desbloqueado violentamente.
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Amostras de código
This example creates a binoculars script that decreases the player's FieldOfView() and MouseDeltaSensitivity() when a player with a MouseEnabled() left mouse clicks. The script also points the player's Camera towards the Vector3 world position of the mouse click.
When the player left mouse clicks again, the player's camera reverts back to the a custom Enum.CameraType with the same field of view and CFrame() as before the player zoomed in with the script.
While the player uses the binoculars, the script locks the player's mouse to the center of the screen by setting the player's MouseBehavior() to LockCenter. The player's camera moves when the player moves their mouse according to the InputObject.Delta property passed by InputChanged() indicating the mouse's Vector2 change in screen position.
In order for this example to work as expected, it should be placed in a LocalScript.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end
By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.
The script is broken into two parts:
- Mobile camera events, which rely on touch events
- Non-mobile camera events, which rely on keyboard input and tracking the user's movement
First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.
Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.
The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.
All of the parts discussed above are combined and shown in the code sample below.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end
MouseDeltaSensitivity
Essa propriedade determina a sensibilidade do Mouse do usuário.
A sensibilidade determina a extensão em que um movimento do mouse físico se traduz em um movimento do mouse no jogo.Isso pode ser usado para ajustar como eventos sensíveis de rastreamento de movimento do mouse, como GetMouseDelta, são para o movimento do mouse.
Essa propriedade não afeta o movimento do ícone do mouse.Nem afeta a configuração de Sensibilidade da Câmera encontrada na aba Configurações do menu Configurações do cliente, que também ajusta a sensibilidade do rastreamento de eventos ao movimento do mouse.
Essa propriedade tem um valor máximo de 10 e um valor mínimo de 0.Um valor mais baixo corresponde a uma sensibilidade mais baixa e um valor mais alto a uma sensibilidade maior.
Quando a sensibilidade é 0, eventos que rastreiam o movimento do mouse ainda dispararão, mas todos os parâmetros e propriedades que indicam a mudança na posição do mouse retornarão Vector2.new() , ou Vector3.new() no caso de InputObject.Delta.Por exemplo, GetMouseDelta sempre retornará (0, 0).
Amostras de código
This example creates a binoculars script that decreases the player's FieldOfView() and MouseDeltaSensitivity() when a player with a MouseEnabled() left mouse clicks. The script also points the player's Camera towards the Vector3 world position of the mouse click.
When the player left mouse clicks again, the player's camera reverts back to the a custom Enum.CameraType with the same field of view and CFrame() as before the player zoomed in with the script.
While the player uses the binoculars, the script locks the player's mouse to the center of the screen by setting the player's MouseBehavior() to LockCenter. The player's camera moves when the player moves their mouse according to the InputObject.Delta property passed by InputChanged() indicating the mouse's Vector2 change in screen position.
In order for this example to work as expected, it should be placed in a LocalScript.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end
MouseEnabled
Essa propriedade descreve se o dispositivo do usuário tem um mouse disponível.Essa propriedade é true quando o dispositivo do usuário tem um mouse disponível e false quando não tem.
local UserInputService = game:GetService("UserInputService")if UserInputService.MouseEnabled thenprint("The user's device has an available mouse!")elseprint("The user's device does not have an available mouse!")end
É importante verificar isso antes de usar UserInputService funções do mouse, como UserInputService:GetMouseLocation().
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Veja também:
Amostras de código
This example creates a binoculars script that decreases the player's FieldOfView() and MouseDeltaSensitivity() when a player with a MouseEnabled() left mouse clicks. The script also points the player's Camera towards the Vector3 world position of the mouse click.
When the player left mouse clicks again, the player's camera reverts back to the a custom Enum.CameraType with the same field of view and CFrame() as before the player zoomed in with the script.
While the player uses the binoculars, the script locks the player's mouse to the center of the screen by setting the player's MouseBehavior() to LockCenter. The player's camera moves when the player moves their mouse according to the InputObject.Delta property passed by InputChanged() indicating the mouse's Vector2 change in screen position.
In order for this example to work as expected, it should be placed in a LocalScript.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head", false)
local mouse = player:GetMouse()
local zoomed = false
local camera = game.Workspace.CurrentCamera
local target = nil
local originalProperties = {
FieldOfView = nil,
_CFrame = nil,
MouseBehavior = nil,
MouseDeltaSensitivity = nil,
}
local AngleX, TargetAngleX = 0, 0
local AngleY, TargetAngleY = 0, 0
-- Reset camera back to CFrame and FieldOfView before zoom
local function ResetCamera()
target = nil
camera.CameraType = Enum.CameraType.Custom
camera.CFrame = originalProperties._CFrame
camera.FieldOfView = originalProperties.FieldOfView
UserInputService.MouseBehavior = originalProperties.MouseBehavior
UserInputService.MouseDeltaSensitivity = originalProperties.MouseDeltaSensitivity
end
local function ZoomCamera()
-- Allow camera to be changed by script
camera.CameraType = Enum.CameraType.Scriptable
-- Store camera properties before zoom
originalProperties._CFrame = camera.CFrame
originalProperties.FieldOfView = camera.FieldOfView
originalProperties.MouseBehavior = UserInputService.MouseBehavior
originalProperties.MouseDeltaSensitivity = UserInputService.MouseDeltaSensitivity
-- Zoom camera
target = mouse.Hit.Position
local eyesight = head.Position
camera.CFrame = CFrame.new(eyesight, target)
camera.Focus = CFrame.new(target)
camera.FieldOfView = 10
-- Lock and slow down mouse
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
UserInputService.MouseDeltaSensitivity = 1
-- Reset zoom angles
AngleX, TargetAngleX = 0, 0
AngleY, TargetAngleY = 0, 0
end
-- Toggle camera zoom/unzoom
local function MouseClick()
if zoomed then
-- Unzoom camera
ResetCamera()
else
-- Zoom in camera
ZoomCamera()
end
zoomed = not zoomed
end
local function MouseMoved(input)
if zoomed then
local sensitivity = 0.6 -- anything higher would make looking up and down harder; recommend anything between 0~1
local smoothness = 0.05 -- recommend anything between 0~1
local delta = Vector2.new(input.Delta.x / sensitivity, input.Delta.y / sensitivity) * smoothness
local X = TargetAngleX - delta.y
local Y = TargetAngleY - delta.x
TargetAngleX = (X >= 80 and 80) or (X <= -80 and -80) or X
TargetAngleY = (Y >= 80 and 80) or (Y <= -80 and -80) or Y
AngleX = AngleX + (TargetAngleX - AngleX) * 0.35
AngleY = AngleY + (TargetAngleY - AngleY) * 0.15
camera.CFrame = CFrame.new(head.Position, target)
* CFrame.Angles(0, math.rad(AngleY), 0)
* CFrame.Angles(math.rad(AngleX), 0, 0)
end
end
local function InputBegan(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
MouseClick()
end
end
local function InputChanged(input, _gameProcessedEvent)
if input.UserInputType == Enum.UserInputType.MouseMovement then
MouseMoved(input)
end
end
if UserInputService.MouseEnabled then
UserInputService.InputBegan:Connect(InputBegan)
UserInputService.InputChanged:Connect(InputChanged)
end
MouseIcon
A propriedade MouseIcon determina a imagem usada como apontador.Se estiver vazio, uma seta padrão é usada.Enquanto o cursor paira sobre determinados objetos de UI, como um ImageButton , TextButton , TextBox ou ProximityPrompt , esta imagem será substituída e ignorada temporariamente.
Para ocultar completamente o cursor, não use não uma imagem transparente. Em vez disso, defina UserInputService.MouseIconEnabled para falso.
Amostras de código
This example changes the user mouse icon to look like a dragon image.
local UserInputService = game:GetService("UserInputService")
-- In order to restore the cursor to what it was set to previously, it will need to be saved to a variable
local savedCursor = nil
local function setTemporaryCursor(cursor: string)
-- Only update the saved cursor if it's not currently saved
if not savedCursor then
savedCursor = UserInputService.MouseIcon
end
UserInputService.MouseIcon = cursor
end
local function clearTemporaryCursor()
-- Only restore the mouse cursor if there's a saved cursor to restore
if savedCursor then
UserInputService.MouseIcon = savedCursor
-- Don't restore the same cursor twice (might overwrite another script)
savedCursor = nil
end
end
setTemporaryCursor("http://www.roblox.com/asset?id=163023520")
print(UserInputService.MouseIcon)
clearTemporaryCursor()
print(UserInputService.MouseIcon)
MouseIconEnabled
Essa propriedade determina se o ícone Mouse é visível quando true o ícone do mouse é visível, quando false não é.
Por exemplo, o trecho de código abaixo oculta o ícone do mouse.
local UserInputService = game:GetService("UserInputService")UserInputService.MouseIconEnabled = false
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Amostras de código
This example hides the mouse icon while the player beings using their keyboard, such as to chat or enter text into a TextBox. The mouse icon reappears when the user resumes mouse input.
This uses the LastInputType() event to determine when the user begins keyboard input and mouse input - based on the value of the lastInputType argument.
In order for this example to work as expected, it should be placed in a LocalScript.
local UserInputService = game:GetService("UserInputService")
local mouseInput = {
Enum.UserInputType.MouseButton1,
Enum.UserInputType.MouseButton2,
Enum.UserInputType.MouseButton3,
Enum.UserInputType.MouseMovement,
Enum.UserInputType.MouseWheel,
}
local keyboard = Enum.UserInputType.Keyboard
local function toggleMouse(lastInputType)
if lastInputType == keyboard then
UserInputService.MouseIconEnabled = false
return
end
for _, mouse in pairs(mouseInput) do
if lastInputType == mouse then
UserInputService.MouseIconEnabled = true
return
end
end
end
UserInputService.LastInputTypeChanged:Connect(toggleMouse)
OnScreenKeyboardPosition
Esta propriedade descreve a posição do teclado na tela em pixels. A posição do teclado é Vector2.new(0, 0) quando não está visível.
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript ou um Script com RunContext definido para Enum.RunContext.Client .
Veja também OnScreenKeyboardVisible e OnScreenKeyboardSize.
Amostras de código
This example prints the position of the player's on-screen keyboard.
local UserInputService = game:GetService("UserInputService")
print(UserInputService.OnScreenKeyboardPosition)
OnScreenKeyboardSize
Essa propriedade descreve o tamanho do teclado na tela em pixels. O tamanho do teclado é Vector2.new(0, 0) quando não está visível.
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript ou um Script com RunContext definido para Enum.RunContext.Client .
Veja também OnScreenKeyboardVisible e OnScreenKeyboardPosition.
OnScreenKeyboardVisible
Essa propriedade descreve se um teclado na tela está atualmente visível na tela do usuário.
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript ou um Script com RunContext definido para Enum.RunContext.Client .
Veja também OnScreenKeyboardSize e OnScreenKeyboardPosition.
TouchEnabled
Essa propriedade descreve se o dispositivo atual do usuário tem uma tela de toque disponível.
A propriedade é usada para determinar se o dispositivo do usuário tem uma tela de toque e, portanto, se os eventos de toque serão Iniciar / executar.Se TouchEnabled for verdadeiro, você pode usar eventos do UserInputService, como UserInputService.TouchStarted e UserInputService.TouchEnded, para rastrear quando um usuário começa e para de tocar na tela de seu dispositivo.
O trecho de código abaixo imprime se o dispositivo do usuário tem tela de toque.
local UserInputService = game:GetService("UserInputService")if UserInputService.TouchEnabled thenprint("The user's device has a touchscreen!")elseprint("The user's device does not have a touchscreen!")end
Veja também:
Amostras de código
By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.
The script is broken into two parts:
- Mobile camera events, which rely on touch events
- Non-mobile camera events, which rely on keyboard input and tracking the user's movement
First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.
Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.
The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.
All of the parts discussed above are combined and shown in the code sample below.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end
VREnabled
Essa propriedade descreve se o usuário está usando um dispositivo de realidade virtual (VR).
Se um dispositivo VR estiver habilitado, você pode interagir com sua localização e movimento através de funções como UserInputService:GetUserCFrame().Você também pode reagir ao movimento do dispositivo VR usando o evento UserInputService.UserCFrameChanged.
local UserInputService = game:GetService("UserInputService")local isUsingVR = UserInputService.VREnabledif isUsingVR thenprint("User is using a VR headset!")elseprint("User is not using a VR headset!")end
Como UserInputService é apenas do lado do cliente, esta propriedade só pode ser usada em um LocalScript.
Veja também:
Amostras de código
This example demonstrates how to implement a head tracking script that mirrors the movement of a virtual reality (VR) headset (the user's actual head) to their in-game character's head.
The example first check if the user is using a VR device by checking the value of the VREnabled() property. This example only works if the user is using a VR headset.
To determine the initial CFrame of the character's head, the code sample calls GetUserCFrame() and passes Enum.UserCFrame.Head as the argument.
To update the head's CFrame whenever the user's VR headset moves, the example connects the VRService.UserCFrameChanged event to the TrackHead() function. When the event fires to indicate that a VR device moved, TrackHead() checks if the headset moved. If the headset moved, the function updates the CFrame of the character's head to the CFrame value provided as an argument.
As the UserCFrame enum also tracks VR left and right hand devices, the concept of VR device tracking can be expanded to other character bodyparts.
In order for the example to work as expected, it must be placed in a LocalScript.
local VRService = game:GetService("VRService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local function TrackHead(inputType, value)
if inputType == Enum.UserCFrame.Head then
head.CFrame = value
end
end
if VRService.VREnabled then
-- Set the initial CFrame
head.CFrame = VRService:GetUserCFrame(Enum.UserCFrame.Head)
-- Track VR headset movement and mirror for character's head
VRService.UserCFrameChanged:Connect(TrackHead)
end
Métodos
GamepadSupports
Essa função retorna se o gamepad dado Enum.UserInputType suporta um botão correspondente ao dado Enum.KeyCode.Essa função é usada para determinar as entradas de gamepad válidas.
Para determinar quais Enum.UserInputType gamepads estão conectados, use UserInputService:GetConnectedGamepads().
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
Parâmetros
O Enum.UserInputType da controle / controle de jogo.
O Enum.KeyCode da botão em questão.
Devolução
Se o gamepad fornecido suporta um botão correspondente ao dado Enum.KeyCode.
Amostras de código
This example binds the ButtonX key to action if it is supported by controller (Gamepad1). If bound, pressing the X Button invokes the action() function, which prints "Action".
local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local controller = Enum.UserInputType.Gamepad1
local buttonX = Enum.KeyCode.ButtonX
local function isSupported(gamepad, keycode)
return UserInputService:GamepadSupports(gamepad, keycode)
end
local function action()
print("Action")
end
if isSupported(controller, buttonX) then
ContextActionService:BindAction("sample action", action, false, buttonX)
end
GetConnectedGamepads
Essa função retorna um array de Enum.UserInputType gamepads atualmente conectados.Se nenhum gamepad estiver conectado, esse array será vazio.Além disso, ele retorna apenas objetos UserInputType que são gamepads.Por instância, este evento retornará um objeto Gamepad1 conectado, mas não um Objetode Teclado.
Por exemplo, o seguinte trecho de código recupera os gamepads conectados e os armazena em uma variável chamada connectedGamepads.
local UserInputService = game:GetService("UserInputService")local connectedGamepads = UserInputService:GetConnectedGamepads()
Para verificar se um gamepad específico está conectado, use UserInputService:GetGamepadConnected() .
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
Devolução
Um conjunto de UserInputTypes correspondendo aos gamepads conectados ao dispositivo do usuário.
Amostras de código
If you are using the default controls, you do not need to worry about this. If you're creating a custom script for handling gamepad controls, this is a good template for retrieving which gamepad enum you should use as the primary gamepad controller.
local UserInputService = game:GetService("UserInputService")
local function getActiveGamepad()
local activeGamepad = nil
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for _, gamepad in connectedGamepads do
if activeGamepad == nil or gamepad.Value < activeGamepad.Value then
activeGamepad = gamepad
end
end
end
if activeGamepad == nil then -- Nothing is connected; set up for "Gamepad1"
activeGamepad = Enum.UserInputType.Gamepad1
end
return activeGamepad
end
if UserInputService.GamepadEnabled then
local activeGamepad = getActiveGamepad()
print(activeGamepad)
end
GetDeviceAcceleration
A função GetDeviceAcceleration determina a aceleração atual do dispositivo do usuário.Ele retorna um InputObject que descreve a aceleração atual do dispositivo.
Para que isso funcione, o dispositivo do usuário deve ter um acelerômetro habilitado.Para verificar se o dispositivo de um usuário tem um acelerômetro habilitado, você pode verificar a propriedade UserInputService.AccelerometerEnabled.
Se você quiser rastrear quando as alterações de aceleração do dispositivo do usuário ocorrem em vez disso, você pode usar o evento UserInputService.DeviceAccelerationChanged.
Como só dispara localmente, só pode ser usado em um LocalScript .
Devolução
Amostras de código
This example checks if a user's device has an enabled accelerometer. If it does, the example prints the current acceleration of the device. If not, the example prints:
Cannot get device acceleration because device does not have an enabled accelerometer!
local UserInputService = game:GetService("UserInputService")
local accelerometerEnabled = UserInputService.AccelerometerEnabled
if accelerometerEnabled then
local acceleration = UserInputService:GetDeviceAcceleration().Position
print(acceleration)
else
print("Cannot get device acceleration because device does not have an enabled accelerometer!")
end
GetDeviceGravity
Essa função retorna um InputObject descrevendo o vetorde gravidade atual do dispositivo.
O vetor de gravidade é determinado pela orientação do dispositivo em relação à força de gravidade do mundo real.Por instância, se um dispositivo estiver perfeitamente ereto (retrato), o vetor de gravidade é Vector3.new(0, 0, -9.18) .Se o lado esquerdo do dispositivo está apontando para baixo, o vetor é Vector3.new(9.81, 0, 0).Finalmente, se a parte de trás do dispositivo está apontando para baixo, o vetor é Vector3.new(0, -9.81, 0).
Essa função pode ser usada para habilitar o dispositivo do usuário a impactar ou controlar a gravidade dentro do jogo ou mover objetos no jogo, como uma bola.
A gravidade é rastreada apenas para jogadores usando um dispositivo com um giroscópio ativado - como um dispositivo móvel.
Para verificar se o dispositivo de um usuário tem um giroscópio ativado, verifique o valor de UserInputService.GyroscopeEnabled .Se o dispositivo tiver um giroscópio ativado, você também pode usar o evento UserInputService.DeviceGravityChanged para rastrear quando a força de gravidade no dispositivo do usuário muda.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Devolução
Amostras de código
Using the Gyroscope gives us the down direction for the player's device. We can use this to move objects in the game world. This example implements a level where the bubble will move along the X and Z axes depending on the device's current gryoscope position in X and Z.
local UserInputService = game:GetService("UserInputService")
local bubble = script.Parent:WaitForChild("Bubble")
local camera = workspace.CurrentCamera
camera.CameraType = Enum.CameraType.Scriptable
camera.CFrame = CFrame.new(0, 20, 0) * CFrame.Angles(-math.pi / 2, 0, 0)
if UserInputService.GyroscopeEnabled then
-- Bind event to when gyroscope detects change
UserInputService.DeviceGravityChanged:Connect(function(accel)
-- Move the bubble in the world based on the gyroscope data
bubble.Position = Vector3.new(-8 * accel.Position.X, 1.8, -8 * accel.Position.Z)
end)
end
GetDeviceRotation
Essa função retorna um InputObject e um CFrame descrevendo o vetor de rotação atual do dispositivo.
Isso é disparado com um InputObject.A propriedade Posição do objeto de entrada é um Enum.InputType.Gyroscope que rastreia a rotação total em cada eixo local.
A rotação do dispositivo só pode ser rastreada em dispositivos com um gyroscope .
Como essa função é executada localmente, ela só pode ser usada em um LocalScript .
Devolução
Um tuple que contém duas propriedades:
- A propriedade delta descreve a quantidade de rotação que aconteceu pela última vez
- O CFrame é a rotação atual do dispositivo em relação ao seu quadro de referência padrão.
Amostras de código
This example prints the current CFrame of a players device. Note that this will only work as expected if the player's device has an enabled gyroscope. If not, the example prints:
Cannot get device rotation because device does not have an enabled gyroscope!
local UserInputService = game:GetService("UserInputService")
local gyroEnabled = UserInputService:GyroscopeEnabled()
if gyroEnabled then
local _inputObj, cframe = UserInputService:GetDeviceRotation()
print("CFrame: {", cframe, "}")
else
print("Cannot get device rotation because device does not have an enabled gyroscope!")
end
GetFocusedTextBox
Essa função retorna o TextBox o cliente está atualmente focado.Um TextBox pode ser selecionado manualmente pelo usuário, ou a seleção pode ser forçada usando a função TextBox:CaptureFocus().Se nenhum TextBox for selecionado, essa função retornará nil .
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também
Devolução
GetGamepadConnected
Essa função retorna se um gamepad com o dado Enum.UserInputType está conectado ao cliente.
Isso pode ser usado para verificar se um controle / controle de jogoespecífico, como 'Gamepad1' está conectado ao dispositivo do cliente.
Para recuperar uma lista de todos os gamepads conectados, use UserInputService:GetConnectedGamepads().
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
Parâmetros
O Enum.UserInputType da gamepad em questão.
Devolução
Se um gamepad associado a Enum.UserInputType está conectado.
Amostras de código
This example returns whether Gamepad1 is connected to the client. It will print true if Gamepad1 is connected and false if Gamepad1 is not connected.
local UserInputService = game:GetService("UserInputService")
local isConnected = UserInputService:GetGamepadConnected(Enum.UserInputType.Gamepad1)
if isConnected then
print("Gamepad1 is connected to the client")
else
print("Gamepad1 is not connected to the client")
end
GetGamepadState
Essa função retorna um array de para todos os inputs disponíveis no controle / controle de jogodado, representando o último estado de entrada de cada input.
Para encontrar o UserInputTypes de gamepads conectados, use UserInputService:GetConnectedGamepads().
Como essa função só é disparada localmente, ela só pode ser usada em um LocalScript .
Veja também:
Parâmetros
O Enum.UserInputType correspondente com o gamepad em questão.
Devolução
Um array de InputObjects representando o estado atual de todos os inputs disponíveis para o controle / controle de jogodado.
GetImageForKeyCode
Este método pega o solicitado Enum.KeyCode e retorna a imagem associada para o dispositivo de gamepad conectado atualmente (limitado ao Xbox, PlayStation e Windows).Isso significa que se o controlador conectado for um Controledo Xbox One, o usuário verá recursos do Xbox.Da mesma forma, se o dispositivo conectado for um Controlede PlayStation, o usuário vê recursos do PlayStation.Se você quiser usar recursos personalizados, veja GetStringForKeyCode() .
Parâmetros
O Enum.KeyCode para o qual obter a imagem associada.
Devolução
O ID do recurso de imagem retornado.
Amostras de código
This API returns the requested image for the given Enum.KeyCode.
local UserInputService = game:GetService("UserInputService")
local imageLabel = script.Parent
local key = Enum.KeyCode.ButtonA
local mappedIconImage = UserInputService:GetImageForKeyCode(key)
imageLabel.Image = mappedIconImage
GetKeysPressed
Essa função retorna um array de InputObjects associado às teclas que estão sendo pressionadas no momento.
Este array pode ser iterado para determinar quais teclas estão sendo pressionadas no momento, usando os valores InputObject.KeyCode .
Para verificar se uma chave específica está sendo pressionada, use UserInputService:IsKeyDown() .
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Devolução
Um array de InputObjects associado às chaves que estão sendo pressionadas no momento.
Amostras de código
This example demonstrates how to use the UserInputService:GetKeysPressed() function to create a combo action where the player double jumps when the player presses actionKey key (Left Shift) + Jump key (Spacebar).
The actionKey variable indicates which key, combined with the Jump key, needs to be pressed for the player to double jump.
When the player presses the Jump key, the JumpRequest() event is invoked, which is connected to the script's jumpRequest function. If the Left Shift key is pressed and the player is not already in the middle of a jump, this function sets the canDoubleJump boolean to true.
The example connects the stateChanged function to the StateChanged() event so that the function fires when their humanoid's state changes. If the state changes from Jumping to Freefall, and the canDoubleJump boolean is true, the function makes the player jump again by setting their humanoid's state back to Jumping using the ChangeState() function . The example also uses the canJump boolean variable to determine when the player is in the middle of a jump. Without this variable, the player could press the actionKey + Jump Key (spacebar) to jump endlessly without landing. When the boolean is true, the player is not jumping. If the player is not jumping, jumpRequest() checks if the actionKey is pressed and sets canJump to false. When the player lands, stateChanged() sets the variable to true.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local actionKey = Enum.KeyCode.LeftShift
local canJump = true
local canDoubleJump = false
local function jumpRequest()
local keysPressed = UserInputService:GetKeysPressed()
for _, key in ipairs(keysPressed) do
if key.KeyCode == actionKey and canJump then
canJump = false
canDoubleJump = true
end
end
end
local function stateChanged(oldState, newState)
-- Double jump during freefall if able to
if oldState == Enum.HumanoidStateType.Jumping and newState == Enum.HumanoidStateType.Freefall and canDoubleJump then
canDoubleJump = false
task.wait(0.2)
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
-- Allow player to jump again after they land
if oldState == Enum.HumanoidStateType.Freefall and newState == Enum.HumanoidStateType.Landed then
canJump = true
end
end
UserInputService.JumpRequest:Connect(jumpRequest)
humanoid.StateChanged:Connect(stateChanged)
GetLastInputType
Essa função retorna 'Enum.UserInputType` associado ao mais recente input do usuário.
Por exemplo, se a entrada anterior do usuário tivesse pressionado a barra de espaço, o retornado Enum.UserInputType seria 'Teclado'.
O evento UserInputService.LastInputTypeChanged pode ser usado para rastrear quando a última Enum.UserInputType usada pelo usuário mudou.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Devolução
O Enum.UserInputType associado com a entrada mais recente do usuário.
Amostras de código
This example gets the last input type and indicates if it was keyboard input.
local UserInputService = game:GetService("UserInputService")
local lastInput = UserInputService:GetLastInputType()
if lastInput == Enum.UserInputType.Keyboard then
print("Most recent input was via keyboard")
end
GetMouseButtonsPressed
Essa função retorna um array de InputObjects correspondente aos botões do mouse que estão sendo pressionados no momento.
Botões do mouse que são rastreados por essa função incluem:
<td>Descrição</td></tr></thead><tr><td>Botão de Mouse1</td><td>O botão do mouse esquerdo.</td></tr><tr><td>Botão de Mouse2</td><td>O botão direito do mouse.</td></tr><tr><td>Botão de Mouse3</td><td>O botão do meio do mouse.</td></tr>
Qual o nome |
---|
Se o usuário não estiver pressionando nenhum botão do mouse quando a função for chamada, ela retornará um matriz / listavazio.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Devolução
Um array de InputObjects correspondente aos botões do mouse que estão sendo pressionados atualmente.
Amostras de código
This example checks if the user pressed MouseButton1, MouseButton2, or both mouse buttons on InputBegan().
The example can be extended to behave differently depending on which mouse buttons are pressed.
local UserInputService = game:GetService("UserInputService")
-- InputBegan is a UserInputService event that fires when the player
-- begins interacting via a Human-User input device
UserInputService.InputBegan:Connect(function(_input, _gameProcessedEvent)
-- Returns an array of the pressed MouseButtons
local buttons = UserInputService:GetMouseButtonsPressed()
local m1Pressed, m2Pressed = false, false
for _, button in pairs(buttons) do
if button.UserInputType.Name == "MouseButton1" then
print("MouseButton1 is pressed")
m1Pressed = true
end
if button.UserInputType.Name == "MouseButton2" then
print("MouseButton2 is pressed")
m2Pressed = true
end
if m1Pressed and m2Pressed then
print("Both mouse buttons are pressed")
end
end
end)
GetMouseDelta
Essa função retorna a mudança, em pixels, da posição do Mouse do jogador na última imagem renderizada como um Vector2.Essa função só funciona se o mouse tiver sido bloqueado usando a propriedade UserInputService.MouseBehavior.Se o mouse não tiver sido bloqueado, os valores retornados de Vector2 serão zero.
A sensibilidade do mouse, determinada nas configurações do cliente e UserInputService.MouseDeltaSensitivity , influenciará o resultado.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Devolução
Mudança no movimento do mouse.
Amostras de código
GetMouseDelta returns the current change in movement of the mouse as a Vector2, but only if the mouse is locked. If the mouse isn't locked the values in the returned Vector2 will be zero. It measures any mouse movement in pixels from the last render step to the current render step. If the user has set their camera sensitivity to be higher or lower than 1 in the in-game menu this will affect the value returned by GetMouseDelta. The camera sensitivity is a multiplier to the amount the camera moves as a result of mouse input.
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local function OnRenderStep()
local delta = UserInputService:GetMouseDelta()
print("The mouse has moved", delta, "since the last step.")
end
RunService:BindToRenderStep("MeasureMouseMovement", Enum.RenderPriority.Input.Value, OnRenderStep)
By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.
The script is broken into two parts:
- Mobile camera events, which rely on touch events
- Non-mobile camera events, which rely on keyboard input and tracking the user's movement
First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.
Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.
The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.
All of the parts discussed above are combined and shown in the code sample below.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end
GetMouseLocation
Essa função retorna um Vector2 representando a localização da tela atual do jogador Mouse em pixels em relação ao canto superior esquerdo.Isso não conta para os Enum.ScreenInsets ; para obter os inserções superiores esquerdas e inferiores direitas, chame GuiService:GetGuiInset() .
Se a localização do ponteiro do mouse estiver fora da tela ou o dispositivo do jogador não tiver um mouse, o valor retornado será não determinado.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Devolução
Amostras de código
This example binds the moveToMouse() to RunService's RenderStep to move the GUI to the location of the player's mouse. It does this by converting the location, a Vector2, into a UDim2.
The example sets the value of the GUI's parent ScreenGui ScreenGui.IgnoreGuiInset property to false force the GUI Inset imposed by Roblox's CoreGuis to be ignored by the ScreenGui and its descendants
In order for this example to work as expected, it should be placed in a LocalScript that is a child of the GUI being moved to the mouse's location.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local gui = script.Parent
local screenGui = gui.Parent
screenGui.IgnoreGuiInset = true
local function moveGuiToMouse()
local mouseLocation = UserInputService:GetMouseLocation()
gui.Position = UDim2.fromOffset(mouseLocation.X, mouseLocation.Y)
end
moveGuiToMouse()
RunService:BindToRenderStep("moveGuiToMouse", 1, moveGuiToMouse)
GetNavigationGamepads
Essa função retorna um array de gamepad UserInputTypes.Esta lista está em ordem decrescente de prioridade, o que significa que pode ser iterada para determinar qual gamepad deve ter controle de navegação.
Se um gamepad conectado é um gamepad de navegação apenas determina qual controle / controle de jogo(s) controla os GUIs de navegação.Isso não influencia os controles de navegação.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
- UserInputService:SetNavigationGamepad() , para habilitar ou desabilitar um gamepad para navegação GUI
- UserInputService:IsNavigationGamepad() , para verificar se um gamepad está habilitado para navegação GUI
- UserInputService:GetConnectedGamepads() , para retornar todos os gamepads conectados independentemente do controle de navegação da GUI
Devolução
Um conjunto de UserInputTypes que pode ser usado para navegação GUI, em ordem decrescente de prioridade.
GetStringForKeyCode
ObterStringForKeyCode retorna uma string que representa uma tecla que o usuário deve pressionar para inserir um dado Enum.KeyCode , mantendo em mente seu layout de teclado.Para códigos chave que exigem que algum modificador seja mantido, esta função retorna a chave a ser pressionada, além do modificador.Veja os exemplos abaixo para uma explicação adicional.
Ao usar o Roblox com um layout de teclado não QWERTY, os códigos de tecla são mapeados para posições equivalentes de QWERTY.Por exemplo, pressionar A na tecla AZERTY resulta em Enum.KeyCode.Q.Este mapeamento pode levar a informações desajustadas em elementos de interface de experiência.Por exemplo, "Pressione M para abrir o mapa" é impreciso em um teclado AZERTY; precisaria ser "Pressione ? para abrir o mapa" que está na mesma posição que M em QWERTY.Essa função resolve esse problema fornecendo a chave real a ser pressionada ao usar layouts de teclado não QWERTY.
local UserInputService = game:GetService("UserInputService")local textLabel = script.Parentlocal mapKey = Enum.KeyCode.MtextLabel.Text = "Press " .. UserInputService:GetStringForKeyCode(mapKey) .. " to open the map"
Exemplos no Teclado QWERTY
<th>Retorno de valor</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.Q</code></td><td><code>Q</code></td></tr><tr><td><code>Enum.KeyCode.W</code></td><td><code>W</code></td></tr><tr><td><code>Enum.KeyCode.Equals</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.At</code></td><td><code>2</code> porque <code>@</code> é digitado com <kbd>Shift</kbd><kbd>2</kbd></td></tr></tbody>
Código-Chave |
---|
Exemplos no Teclado AZERTY
<th>Retorno de valor</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.Q</code></td><td><code>A</code></td></tr><tr><td><code>Enum.KeyCode.W</code></td><td><code>Z</code></td></tr><tr><td><code>Enum.KeyCode.Equals</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.At</code></td><td><code>É</code></td></tr></tbody>
Código-Chave |
---|
Uso do Gamepad
GetStringForKeyCode() retorna o mapeamento de corda para o Enum.KeyCode mais recentemente conectado controle / controle de jogo.Se o controlador conectado não for suportado, a função retorna a conversão de string padrão para o código de chave solicitado.
O seguinte exemplo mostra como você pode mapear recursos personalizados para ButtonA :
local UserInputService = game:GetService("UserInputService")local imageLabel = script.Parentlocal key = Enum.KeyCode.ButtonAlocal mappings = {ButtonA = "rbxasset://BUTTON_A_ASSET", -- Replace with the desired ButtonA assetButtonCross = "rbxasset://BUTTON_CROSS_ASSET" -- Replace with the desired ButtonCross asset}local mappedKey = UserInputService:GetStringForKeyCode(key)local image = mappings[mappedKey]imageLabel.Image = image
Mapeamentos de Gamepad
Os códigos da tecla do painel direcional não têm diferenças com base no dispositivo.Enum.KeyCode.ButtonSelect tem comportamento ligeiramente diferente em alguns casos.Use ambas as mapeamentos da PlayStation para garantir que os usuários vejam os botões corretos.
<th>Valor de Retorno da PlayStation</th><th>Valor de retorno do Xbox</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonA</code></td><td><code>BotãoCross</code></td><td><code>BotãoA</code></td></tr><tr><td><code>Enum.KeyCode.ButtonB</code></td><td><code>BotãoCircle</code></td><td><code>BotãoB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonX</code></td><td><code>Botão Quadrado</code></td><td><code>BotãoX</code></td></tr><tr><td><code>Enum.KeyCode.ButtonY</code></td><td><code>Triângulo de Botão</code></td><td><code>BotãoY</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><code>BotãoL1</code></td><td><code>BotãoLB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL2</code></td><td><code>BotãoL2</code></td><td><code>BotãoLT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL3</code></td><td><code>BotãoL3</code></td><td><code>BotõesLS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><code>BotãoR1</code></td><td><code>BotãoRB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR2</code></td><td><code>BotãoR2</code></td><td><code>BotãoRT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><code>BotãoR3</code></td><td><code>BotãoRS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonStart</code></td><td><code>Opções de Botão</code></td><td><code>Início de Botão</code></td></tr><tr><td><code>Enum.KeyCode.ButtonSelect</code></td><td><code>Botão Touchpad</code> e <code>Botão Compartilhar</code></td><td><code>BotãoSelecionar</code></td></tr></tbody>
Código-Chave |
---|
Imagens do sistema para KeyCommands
Ao usar um Enum.KeyCode que pode ser melhor representado como uma imagem, como para um ImageLabel em uma interface do usuário, você pode usar os seguintes ícones legados.No entanto, é recomendado que você use GetImageForKeyCode() como um método mais moderno e cross‑platform para recuperar os ícones de controlador do Xbox e da PlayStation.
<th>Imagem</th><th>ID de recurso</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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/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://texturas/ui/Controls/shift.png</code></td></tr><tr><td><code>Enum.KeyCode.Shift Direito</code></td><td><img src="../../../assets/scripting/controls/shift.png" width="24"></img></td><td><code>rbxasset://texturas/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://texturas/ui/Controls/tab.png</code></td></tr><tr><td><code>Enum.KeyCode.Quote</code></td><td><img src="../../../assets/scripting/controls/apostrophe.png" width="24"></img></td><td><code>rbxasset://texturas/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://texturas/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://texturas/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://texturas/ui/Controls/period.png</code></td></tr><tr><td><code>Enum.KeyCode.Espaço</code></td><td><img src="../../../assets/scripting/controls/spacebar.png" width="24"></img></td><td><code>rbxasset://texturas/ui/Controls/barra de espaço.png</code></td></tr></tbody>
Código-Chave |
---|
Parâmetros
Devolução
GetSupportedGamepadKeyCodes
Essa função retorna um array de KeyCodes que o gamepad associado ao dado Enum.UserInputType suporta.
Essa função pode ser usada para determinar quais KeyClasses são suportadas e não são suportadas por um controle / controle de jogoconectado.Para determinar se um código de chave específico é suportado, use UserInputService:GamepadSupports() .
Se chamado em um controle / controle de jogonão existente ou não conectado, esta função retornará um matriz / listavazio.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
Parâmetros
O Enum.UserInputType da controle / controle de jogo.
Devolução
Amostras de código
This example gets a list of navigation gamepads and a list of their supported Enum.KeyCodes. Then, it iterates through the supported KeyCode list and binds the ButtonX and X keys to functions if they are supported by a gamepad using the ContextActionService.
local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local function actionHandler(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
print("Action Handler: " .. actionName)
print(inputObject)
end
-- Since this function does not return anything, this handler will
-- "sink" the input and no other action handlers will be called after
-- this one.
end
local navGamepads = UserInputService:GetNavigationGamepads()
for _, gamepad in pairs(navGamepads) do
local supportedKeyCodes = UserInputService:GetSupportedGamepadKeyCodes(gamepad)
for _, keycode in pairs(supportedKeyCodes) do
if keycode == Enum.KeyCode.ButtonX then
ContextActionService:BindAction("SampleAction", actionHandler, false, Enum.KeyCode.ButtonX)
end
if keycode == Enum.KeyCode.X then
ContextActionService:BindAction("SampleAction", actionHandler, false, Enum.KeyCode.X)
end
end
end
IsGamepadButtonDown
Essa função verifica se um botão específico é pressionado em um controle / controle de jogoespecífico.Ele retorna true se o gamepad tiver apertado o especificado button pressionado, caso contrário, retorna falso.
Tipos de Entrada de Usuário válidos
O controlador especificado deve ser um dos seguintes valores de enumeração de Tipo de Entrada do Usuário:
<tr><td>Enum.UserInputType.Gamepad1-8</td></tr>
Qual o nome |
---|
Teclados válidos
O botão especificado deve ser um dos seguintes valores de enumeração de KeyCodec:
<tr><td>Enum.KeyCode.ButtonX</td></tr><tr><td>Enum.KeyCode.ButtonY</td></tr><tr><td>Enum.KeyCode.ButtonA</td></tr><tr><td>Enum.KeyCode.ButtonB</td></tr><tr><td>Enum.KeyCode.ButtonR1</td></tr><tr><td>Enum.KeyCode.ButtonL1</td></tr><tr><td>Enum.KeyCode.ButtonR2</td></tr><tr><td>Enum.KeyCode.ButtonL2</td></tr><tr><td>Enum.KeyCode.ButtonR3</td></tr><tr><td>Enum.KeyCode.ButtonL3</td></tr><tr><td>Enum.KeyCode.ButtonStart</td></tr><tr><td>Enum.KeyCode.ButtonSelect</td></tr><tr><td>Enum.KeyCode.DPadLeft</td></tr><tr><td>Enum.KeyCode.DPadRight</td></tr><tr><td>Enum.KeyCode.DPadUp</td></tr><tr><td>Enum.KeyCode.DPadDown</td></tr>
Qual o nome |
---|
Isso pode ser usado para verificar se um botão específico, como A, está sendo mantido pressionado. Por exemplo:
local UserInputService = game:GetService("UserInputService")local button = Enum.KeyCode.ButtonAlocal gamepad = Enum.UserInputType.Gamepad1local isButtonHeld = UserInputService:IsGamepadButtonDown(gamepad, button)
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
- UserInputService:IsKeyDown() - Um método similar com um uso diferente: Para verificar se um dado key em um keyboard é pressionado.
Parâmetros
O Enum.UserInputType da controle / controle de jogodada.
O Enum.KeyCode da botão especificado.
Devolução
Se o botão de gamepad especificado no gamepad dado for pressionado é pressionado.
Amostras de código
This example uses the UserInputService:IsGamepadButtonDown() function to create different behaviors when the X gamepad button is pressed than when a X button is not pressed when user input UserInputBegan|begins.
The local function IsGamepadXDown() returns whether the X gamepad button is down. This function checks if the X button is down for the activeGamepad, which is set by GetActiveGamepad. The GetActiveGamepad() fnction finds the lowest numbered navigation gamepad, connected gamepad, or gamepad1 if there are no navigation or connected gamepads.
local UserInputService = game:GetService("UserInputService")
local activeGamepad = nil
local buttonX = Enum.KeyCode.ButtonX
local function isGamepadXDown()
if activeGamepad then
return UserInputService:IsGamepadButtonDown(activeGamepad, buttonX)
end
return false
end
local function input(_input, _gameProcessedEvent)
if not isGamepadXDown() then
-- Normal event
else
-- X Button down event
end
end
local function getActiveGamepad()
local activateGamepad = nil
local navigationGamepads = {}
navigationGamepads = UserInputService:GetNavigationGamepads()
if #navigationGamepads > 1 then
for i = 1, #navigationGamepads do
if activateGamepad == nil or navigationGamepads[i].Value < activateGamepad.Value then
activateGamepad = navigationGamepads[i]
end
end
else
local connectedGamepads = {}
connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for i = 1, #connectedGamepads do
if activateGamepad == nil or connectedGamepads[i].Value < activateGamepad.Value then
activateGamepad = connectedGamepads[i]
end
end
end
if activateGamepad == nil then -- nothing is connected, at least set up for gamepad1
activateGamepad = Enum.UserInputType.Gamepad1
end
end
return activateGamepad
end
if UserInputService.GamepadEnabled then
activeGamepad = getActiveGamepad()
UserInputService.InputBegan:Connect(input)
end
IsKeyDown
Essa função retorna se o usuário está pressionando a tecla associada ao dado Enum.KeyCode.Ele retorna true se a chave especificada for pressionada ou false se não for pressionada.
Isso pode ser usado para verificar se uma chaveespecífica, como a barra de espaço, está sendo pressionada. Por exemplo:
local UserInputService = game:GetService("UserInputService")local spaceHeld = UserInputService:IsKeyDown(Enum.KeyCode.Space)
Para recuperar uma lista de todas as teclas pressionadas pelo usuário, use a função UserInputService:GetKeysPressed().
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
- Enum.UserInputType.IsGamepadButtonDown - Um evento similar com um uso diferente: Para verificar se um determinado button em um gamepad é pressionado.
Parâmetros
O Enum.KeyCode da chave.
Devolução
Se a chave especificada está sendo mantida pressionada.
Amostras de código
This example uses the UserInputService:IsKeyDown() function to create different behaviors when a shift key is held down than when a shift key is not held down when user input UserInputBegan|begins.
The local function IsShiftKeyDown() returns whether the left or right shift keys are pressed.
local UserInputService = game:GetService("UserInputService")
local shiftKeyL = Enum.KeyCode.LeftShift
local shiftKeyR = Enum.KeyCode.RightShift
-- Return whether left or right shift keys are down
local function isShiftKeyDown()
return UserInputService:IsKeyDown(shiftKeyL) or UserInputService:IsKeyDown(shiftKeyR)
end
-- Handle user input began differently depending on whether a shift key is pressed
local function input(_input, _gameProcessedEvent)
if not isShiftKeyDown() then
-- Normal input
else
-- Shift input
end
end
UserInputService.InputBegan:Connect(input)
IsMouseButtonPressed
Essa função toma um botão do mouse Enum.UserInputType e retorna um bool que indica se está pressionado atualmente.
O botão do mouse verificado depende do valor Enum.UserInputType passado para a função como argumento. Por exemplo:
local UserInputService = game:GetService("UserInputService")local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript."
Parâmetros
O Enum.UserInputType da tecla do mouse.
Devolução
Se o botão de mouse dado está atualmente pressionado.
Amostras de código
By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.
The script is broken into two parts:
- Mobile camera events, which rely on touch events
- Non-mobile camera events, which rely on keyboard input and tracking the user's movement
First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.
Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.
The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.
All of the parts discussed above are combined and shown in the code sample below.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end
IsNavigationGamepad
Essa função retorna true se o gamepad especificado Enum.UserInputType for permitido controlar Navegação e Seleção GuiObjects .
Se você quiser definir um controle / controle de jogode navegação, você pode usar UserInputService:SetNavigationGamepad() . Você também pode usar UserInputService:GetNavigationGamepads() para obter uma lista de todos os gamepads de navegação.
Por exemplo, o código abaixo verifica se o gamepad1 é como um controle / controle de jogode navegação:
local UserInputService = game:GetService("UserInputService")if UserInputService:IsNavigationGamepad(UserInputType.Gamepad1) thenprint("Gamepad is a navigation gamepad!")elseprint("Gamepad is not a navigation gamepad!")end
Uma lista de todos os gamepads conectados, independentemente da navegação, pode ser recuperada usando `UserInput/GetConnectedGamepads.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
Parâmetros
O Enum.UserInputType da controle / controle de jogoespecificada.
Devolução
Se o controlador especificado é um controle / controle de jogode navegação.
RecenterUserHeadCFrame
Essa função recoloca o CFrame da fone de ouvido VR na orientação atual do fone de ouvido usado pelo usuário.Isso significa que a orientação atual do óculosde ouvido é definida como CFrame.new() .
Use essa função para mover o fone de ouvido CFrame para o centro da área de reprodução se parecer estar em um deslocamento estranho.
Isso se comporta de forma idêntica à função VRService , VRService:RecenterUserHeadCFrame() .
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Devolução
Amostras de código
This example fires the function to recenter the CFrame of the user's head to the current location of the VR headset being worn by the user.
local UserInputService = game:GetService("UserInputService")
UserInputService:RecenterUserHeadCFrame()
SetNavigationGamepad
A função SetNavigationGamepad define se o gamepad especificado Enum.UserInputType pode mover o navegador da GUI.Um gamepad que é permitido mover o navegador da GUI é considerado um gamepad de navegação.
Se o argumento habilitado for passado como true, o Gamepad pode mover o navegador da GUI.Se o argumento for false, o Gamepad não pode mover o navegador da GUI.
Se você quiser verificar se um Gamepad específico está definido para ser um controle / controle de jogode navegação, você pode usar a função UserInputService:IsNavigationGamepad().Você também pode usar o UserInputService:GetNavigationGamepads() para recuperar uma lista de todos os gamepads de navegação.
Como UserInputService é apenas do lado do cliente, essa função só pode ser usada em um LocalScript.
Veja também:
Parâmetros
O Enum.UserInputType da controle / controle de jogoespecificada.
Se o gamepad especificado pode mover o navegador da GUI.
Devolução
Amostras de código
This example sets Gamepad1 as a navigation gamepad by passing Enum.UserInputType.Gamepad1 and true as arguments.
local UserInputService = game:GetService("UserInputService")
UserInputService:SetNavigationGamepad(Enum.UserInputType.Gamepad1, true)
Eventos
DeviceAccelerationChanged
O evento DeviceAccelerationChanged é disparado quando um usuário move um dispositivo que tem um acelerômetro.
Um acelerômetro é um componente encontrado na maioria dos dispositivos móveis que mede aceleração (mudança na velocidade).
Para determinar se o dispositivo de um usuário tem um acelerômetro ativado, veja UserInputService.AccelerometerEnabled .
Este evento pode ser usado para rastrear o movimento de um dispositivo que tem um acelerômetro.Um uso de amostra inclui mover o personagem do jogador quando um dispositivo móvel acelera.
Além disso, este evento pode ser usado junto com UserInputService:GetDeviceAcceleration() para determinar o movimento atual do dispositivo de um usuário se o dispositivo tiver um acelerômetro.
Este evento só dispara localmente - o que significa que apenas o jogador cujo dispositivo se move pode usar o evento e ele só funcionará em um LocalScript .
Parâmetros
Um InputObject , com um UserInputType de 'Acelerômetro' e Position que mostra a força da gravidade em cada eixo local.
Amostras de código
This example uses the accelerometer to move the player character when a mobile device is accelerated. The character will move along the axis that the device was moved.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local SENSITIVITY = 0.2
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local ready = true
local function changeAcceleration(acceleration)
if ready then
ready = false
local accel = acceleration.Position
if accel.Y >= SENSITIVITY then
humanoid.Jump = true
end
if accel.Z <= -SENSITIVITY then
humanoid:Move(Vector3.new(-1, 0, 0))
end
if accel.Z >= SENSITIVITY then
humanoid:Move(Vector3.new(1, 0, 0))
end
if accel.X <= -SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, 1))
end
if accel.X >= SENSITIVITY then
humanoid:Move(Vector3.new(0, 0, -1))
end
task.wait(1)
ready = true
end
end
UserInputService.DeviceAccelerationChanged:Connect(changeAcceleration)
DeviceGravityChanged
O evento ocorre quando a gravidade do dispositivo muda em um dispositivo que tem um acelerômetro.
O vetor de gravidade de um dispositivo representa a força da gravidade em cada um dos eixos X, Y e Z do dispositivo.Embora a gravidade nunca mude, a força que ela exerce em cada eixo muda quando o dispositivo gira e muda de orientação.O valor da força exercida em cada eixo é um vetor de unidade que varia de -1 a 1.
Um acelerômetro é um componente encontrado na maioria dos dispositivos móveis que mede aceleração (mudança na velocidade).
Este evento pode ser usado para determinar a direção do mundo real da força da gravidade em um dispositivo do usuário.Isso pode então ser usado para simular a força da gravidade em um dispositivo do usuário dentro do jogo, como em objetos no jogo (veja exemplo abaixo).
Para verificar se o dispositivo de um usuário tem um acelerômetro habilitado, veja UserInputService.AccelerometerEnabled .Se o dispositivo tiver um acelerômetro ativado, você pode usar a função UserInputService:GetDeviceGravity() para obter a força atual da gravidade no dispositivo do usuário.
Parâmetros
Um InputObject , com uma propriedade InputObject.Position que mostra a força da gravidade em cada eixo local.Essa posição pode ser usada como uma direção para determinar a direção da gravidade em relação ao dispositivo.
Amostras de código
This code adds a force on a part so that it falls in the direction of actual gravity relative to the user's device.
In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have an accelerometer.
local Workspace = game:GetService("Workspace")
local UserInputService = game:GetService("UserInputService")
local ball = script.Parent:WaitForChild("Ball")
local mass = ball:GetMass()
local gravityForce = ball:WaitForChild("GravityForce")
local function moveBall(gravity)
gravityForce.Force = gravity.Position * Workspace.Gravity * mass
end
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceGravityChanged:Connect(moveBall)
end
This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.
The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:
camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *currentRotation
The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.
The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.
Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.
In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_rotation, rotCFrame)
if orientationSet then
if not lastInputFrame then
lastInputFrame = rotCFrame
end
local delta = rotCFrame * lastInputFrame:inverse()
local x, y, z = delta:ToEulerAnglesXYZ()
if upsideDown then
delta = CFrame.Angles(-x, y, z)
else
delta = CFrame.Angles(x, -y, z)
end
currentRotation = currentRotation * delta
lastInputFrame = rotCFrame
end
end
local function HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end
DeviceRotationChanged
O evento DeviceRotationChanged é disparado quando um usuário gira um dispositivo que tem um giroscópio.
Um giroscópio é um componente encontrado na maioria dos dispositivos móveis que detecta orientação e velocidade de rotação.
O evento é útil ao rastrear a orientação do dispositivo e como as alterações ocorrem quando o usuário gira seu dispositivo.Para determinar a rotação do dispositivo atual, você pode usar a função UserInputService:GetDeviceRotation().
Para verificar se o dispositivo de um usuário tem um giroscópio ativado e que esse evento será Iniciar / executar, veja UserInputService.GyroscopeEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Parâmetros
Um InputObject fornecendo informações sobre a rotação do dispositivo.InputObject.Position representa a nova rotação um Vector3 valor posicional e InputObject.Delta representa a mudança na rotação em um Vector3 valor posicional.
Amostras de código
This example controls the player's Camera so that it matches the player's device orientation via using the device's gyroscope and accelerometer.
The camera is positioned inside the player's head, and updated to move with the player and the user's device rotation, by executing the following line every RenderStep:
camera.CFrame = CFrame.new(head.Position - Vector3.new(0,8,10)) *currentRotation
The code sample relies on the device's gyroscope to determine when the player rotates their device. It does so by connecting to the DeviceRotationChanged() event.
The code sample relies on the device's accelerometer to retrieve the gravity vector used to determine the device's orientation (whether it is flipped upside down or not). To determine whether the device's orientation is upside down, the code sample uses the DeviceGravityChanged() event.
Since the script places the camera inside the head to create a first-person camera, the limbs are made transparent by the HideCharacter() function so that the player does not see their Player.Character when rotating the camera.
In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have a gyroscope and an accelerometer.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local camera = workspace.CurrentCamera
local currentRotation = camera.CFrame -- CFrame.new(Vector3.new(0,0,0), Vector3.new(0,0,0))
local lastInputFrame = nil
local upsideDown = false
task.wait()
local orientationSet = false
local function GravityChanged(gravity)
if not orientationSet then
upsideDown = (gravity.Position.X < -0.5 or gravity.Position.Z > 0.5)
orientationSet = true
end
end
local function RotationChanged(_rotation, rotCFrame)
if orientationSet then
if not lastInputFrame then
lastInputFrame = rotCFrame
end
local delta = rotCFrame * lastInputFrame:inverse()
local x, y, z = delta:ToEulerAnglesXYZ()
if upsideDown then
delta = CFrame.Angles(-x, y, z)
else
delta = CFrame.Angles(x, -y, z)
end
currentRotation = currentRotation * delta
lastInputFrame = rotCFrame
end
end
local function HideCharacter()
for _, limb in pairs(character:GetChildren()) do
if limb:IsA("Part") then
limb.Transparency = 1
end
end
end
if UserInputService.GyroscopeEnabled then
UserInputService.DeviceGravityChanged:Connect(GravityChanged)
UserInputService.DeviceRotationChanged:Connect(RotationChanged)
HideCharacter()
RunService:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, function()
camera.CFrame = CFrame.new(head.Position - Vector3.new(0, 8, 10)) * currentRotation
camera.Focus = CFrame.new(currentRotation * Vector3.new(0, 0, -10))
end)
end
This code adds a force on a part so that it falls in the direction of actual gravity relative to the user's device.
In order for this example to work as expected, it must be placed in a LocalScript and the user's device must have an accelerometer.
local Workspace = game:GetService("Workspace")
local UserInputService = game:GetService("UserInputService")
local ball = script.Parent:WaitForChild("Ball")
local mass = ball:GetMass()
local gravityForce = ball:WaitForChild("GravityForce")
local function moveBall(gravity)
gravityForce.Force = gravity.Position * Workspace.Gravity * mass
end
if UserInputService.AccelerometerEnabled then
UserInputService.DeviceGravityChanged:Connect(moveBall)
end
GamepadConnected
O evento GamepadConnected é acionado quando um gamepad é conectado ao cliente.
Como um jogo do Roblox suporta vários controladores, este evento é útil quando combinado com o evento para rastrear quais controladores/gamepads estão ativos.Você também pode usar UserInputService:GetConnectedGamepads() para encontrar o gamepad correto para usar.
O seguinte exemplo demonstra um exemplo de uso de rastreamento quando um gamepad é conectado ao cliente.
local UserInputService = game:GetService("UserInputService")
local function GamepadConnected(gamepad)
print("Player has plugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadConnected:Connect(GamepadConnected)
Se você quiser ver quais dispositivos estão conectados, você pode usar a função UserInputService:GetConnectedGamepads().
Como este evento é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
O Enum.UserInputType da controle / controle de jogoconectada.
GamepadDisconnected
O evento GamepadDisconnected é acionado quando um gamepad é desconectado.
Como um jogo do Roblox suporta vários controladores, este evento é útil quando combinado com o evento para rastrear quais controladores/gamepads estão ativos.Você também pode usar UserInputService:GetConnectedGamepads() para encontrar o gamepad correto para usar.
O seguinte exemplo demonstra um exemplo de uso de rastreamento quando um gamepad é desconectado do cliente.
local UserInputService = game:GetService("UserInputService")
local function GamepadDisconnected(gamepad)
print("Player has unplugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadDisconnected:Connect(GamepadDisconnected)
Como este evento é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
O Enum.UserInputType da controle / controle de jogodesconectada.
InputBegan
O evento InputBegan é acionado quando um usuário começa a interagir através de um dispositivo de Interface Humano-Computador (botão do mouse para baixo, toque começar, botão de teclado para baixo, etc.).
Pode ser usado para rastrear o início da interação do usuário, como quando um usuário interage pela primeira vez com um elemento de GUI, um controle / controle de jogo, etc.Não captura os movimentos da roda do mouse.
Este evento pode ser usado junto com UserInputService.InputChanged e UserInputService.InputEnded para rastrear quando a entrada do usuário começa, muda e termina.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Parâmetros
Uma instância InputObject que contém informações sobre a entrada do usuário.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The following example demonstrates one of many usage examples of handling user input from InputBegan depending on its type.
-- In order to use the InputBegan event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- A sample function providing multiple usage cases for various types of user input
UserInputService.InputBegan:Connect(function(input, gameProcessed)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key is being pushed down! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been pressed down at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has started at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button is being pressed on a gamepad! Button:", input.KeyCode)
end
if gameProcessed then
print("The game engine internally observed this input!")
else
print("The game engine did not internally observe this input!")
end
end)
InputChanged
O evento InputChanged é acionado quando um usuário muda como está interagindo através de um dispositivo de Interface Humano-Computador (botão do mouse para baixo, toque começa, botão do teclado para baixo, etc).
Para ignorar eventos que são automaticamente tratados pelo Roblox, como rolagem em um ScrollingFrame, verifique se o argumento evento processado pelo jogo é falso.Este evento pode ser usado junto com UserInputService.InputBegan e UserInputService.InputEnded para rastrear quando a entrada do usuário começa, muda e termina.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Parâmetros
Uma instância InputObject que contém informações sobre a entrada do usuário.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The following example demonstrates one of many usage examples of handling user input from InputChanged depending on its type.
-- In order to use the InputChanged event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- Prints the current input position and the change (delta) in position
local function printMovement(input)
print("Position:", input.Position)
print("Movement Delta:", input.Delta)
end
-- A sample function providing multiple usage cases for various types of user input
local function InputChanged(input, _gameProcessed)
if input.UserInputType == Enum.UserInputType.MouseMovement then
print("The mouse has been moved!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
print("The mouse wheel has been scrolled!")
print("Wheel Movement:", input.Position.Z)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
if input.KeyCode == Enum.KeyCode.Thumbstick1 then
print("The left thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.Thumbstick2 then
print("The right thumbstick has been moved!")
printMovement(input)
elseif input.KeyCode == Enum.KeyCode.ButtonL2 then
print("The pressure being applied to the left trigger has changed!")
print("Pressure:", input.Position.Z)
elseif input.KeyCode == Enum.KeyCode.ButtonR2 then
print("The pressure being applied to the right trigger has changed!")
print("Pressure:", input.Position.Z)
end
elseif input.UserInputType == Enum.UserInputType.Touch then
print("The user's finger is moving on the screen!")
printMovement(input)
elseif input.UserInputType == Enum.UserInputType.Gyro then
local _rotInput, rotCFrame = UserInputService:GetDeviceRotation()
local rotX, rotY, rotZ = rotCFrame:toEulerAnglesXYZ()
local rot = Vector3.new(math.deg(rotX), math.deg(rotY), math.deg(rotZ))
print("The rotation of the user's mobile device has been changed!")
print("Position", rotCFrame.p)
print("Rotation:", rot)
elseif input.UserInputType == Enum.UserInputType.Accelerometer then
print("The acceleration of the user's mobile device has been changed!")
printMovement(input)
end
end
UserInputService.InputChanged:Connect(InputChanged)
InputEnded
O evento InputEnded é acionado quando um usuário para de interagir através de um dispositivo de Interface Humano-Computador (botão do mouse para baixo, toque começar, botão de teclado para baixo, etc).Isso é útil ao rastrear quando um usuário libera uma chavede teclado, botão do mouse, entrada do touchscreen, etc.
Este evento pode ser usado junto com UserInputService.InputBegan e UserInputService.InputChanged para rastrear quando a entrada do usuário começa, muda e termina.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Parâmetros
Uma instância InputObject que contém informações sobre a entrada do usuário.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The following example demonstrates one of many usage examples of handling user input from InputEnded depending on its type.
-- In order to use the InputChanged event, the UserInputService service must be used
local UserInputService = game:GetService("UserInputService")
-- A sample function providing multiple usage cases for various types of user input
UserInputService.InputEnded:Connect(function(input, gameProcessed)
if input.UserInputType == Enum.UserInputType.Keyboard then
print("A key has been released! Key:", input.KeyCode)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
print("The right mouse button has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Touch then
print("A touchscreen input has been released at", input.Position)
elseif input.UserInputType == Enum.UserInputType.Gamepad1 then
print("A button has been released on a gamepad! Button:", input.KeyCode)
end
if gameProcessed then
print("The game engine internally observed this input!")
else
print("The game engine did not internally observe this input!")
end
end)
JumpRequest
O evento de solicitação de pulo UserInputService é acionado quando há um pedido de pulo do cliente, por exemplo, quando o cliente pressiona a barra de espaço ou o botão de pulo no celular.
Este evento dispara sempre que o usuário tenta fazer seu pulo Player.Character .O comportamento padrão responde a um pedido de pulo definindo a propriedade do jogador Humanoid.Jump para verdadeiro, o que faz o personagem do jogador pular.
O evento pode ser usado para rastrear todas as vezes que um jogador quer pular.Em vez de usá-lo para fazer um jogador pular, isso deve ser usado para alterar o comportamento padrão de pulo - como desabilitar o pulo.
Por exemplo, o código abaixo imprime "Pular" sempre que o jogador envia um solicitar / pedirde pulo.
local UserInputService = game:GetService("UserInputService")
function onJumpRequest()
print("Jump!")
end
UserInputService.JumpRequest:Connect(onJumpRequest)
Como este evento dispara várias vezes para um único solicitar / pedirde pulo, usar um desbounce é sugerido.
Se você quiser conectar chaves ou botões a outras ações, considere usar eventos como UserInputService:GetKeysPressed() e UserInputService.InputBegan ou o ContextActionService.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Amostras de código
This code sample disables jumping for the LocalPlayer by setting the Enum.HumanoidStateType.Jumping state to false. Setting this state to false as soon as the user tries to jump cancels the jump.
In order for this example to work as expected, it should be placed in a LocalScript.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
-- Fires when the user tries to jump
local function jump()
humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
end
UserInputService.JumpRequest:Connect(jump)
LastInputTypeChanged
O evento UserInputService.LastInputTypeChanged ocorre sempre que o cliente muda como está interagindo através de um dispositivo de Interface Humano-Computador.(i.e.de MouseMovement para MouseWheel ou de Thumbstick1 para Thumbstick2).
Para obter o valor do último digitarde entrada, independentemente de ter sido alterado ou não, você pode usar a função UserInputService:GetLastInputType().
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Parâmetros
Um Enum.UserInputType indicando o último digitarde entrada.
Amostras de código
This example hides the mouse icon while the player beings using their keyboard, such as to chat or enter text into a TextBox. The mouse icon reappears when the user resumes mouse input.
This uses the LastInputType() event to determine when the user begins keyboard input and mouse input - based on the value of the lastInputType argument.
In order for this example to work as expected, it should be placed in a LocalScript.
local UserInputService = game:GetService("UserInputService")
local mouseInput = {
Enum.UserInputType.MouseButton1,
Enum.UserInputType.MouseButton2,
Enum.UserInputType.MouseButton3,
Enum.UserInputType.MouseMovement,
Enum.UserInputType.MouseWheel,
}
local keyboard = Enum.UserInputType.Keyboard
local function toggleMouse(lastInputType)
if lastInputType == keyboard then
UserInputService.MouseIconEnabled = false
return
end
for _, mouse in pairs(mouseInput) do
if lastInputType == mouse then
UserInputService.MouseIconEnabled = true
return
end
end
end
UserInputService.LastInputTypeChanged:Connect(toggleMouse)
PointerAction
Ação de Apontador dispara quando o usuário realiza uma ação de apontador específica. Em particular, rolar a roda do mouse.
Parâmetros
TextBoxFocusReleased
O evento TextBoxFocusReleased ocorre quando um cliente perde o foco em um TextBox , geralmente quando um cliente interrompe a entrada de texto pressionando retorno ou clicando/tocando em outro lugar na tela.
Por exemplo, o código abaixo imprime o nome do TextBox perdendo o foco quando o evento é disparado.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocusReleased(textbox)
print(textbox.Name)
end
UserInputService.TextBoxFocusReleased:Connect(TextBoxFocusReleased)
Pode ser usado ao lado de UserInputService.TextBoxFocused para rastrear quando um TextBox ganha e perde foco.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também
Parâmetros
TextBoxFocused
Este evento dispara quando um ganha foco em um TextBox, geralmente quando um cliente clica/toca em uma caixa de texto para começar a digitar texto.Isso também dispara se um foco de caixa de texto for focado usando TextBox:CaptureFocus() .
Por exemplo, o código abaixo imprime o nome do TextBox focado quando o evento é disparado.
local UserInputService = game:GetService("UserInputService")
function TextBoxFocused(textbox)
print(textbox.Name)
end)
UserInputService.TextBoxFocused:Connect(TextBoxFocused)
Pode ser usado ao lado de UserInputService.FocusReleased para rastrear quando uma caixa de texto ganha e perde foco.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também
Parâmetros
TouchDrag
Parâmetros
TouchEnded
O evento TouchEnded é acionado quando um usuário libera seu dedo da tela de um dispositivo TouchEnabled, terminando a entrada de toque com o dispositivo.
Este evento pode ser usado para determinar quando um usuário para de tocar na tela do seu dispositivo.Pode ser emparelhado com UserInputService.TouchStarted para determinar quando um usuário começa e para de tocar na tela.
Por exemplo, o código abaixo imprime a posição da tela onde o usuário para de tocar na tela.
local UserInputService = game:GetService("UserInputService")
function TouchEnded(touch, gameProcessedEvent)
print("Touch ended at " .. tostring(touch.Position))
end
UserInputService.TouchEnded:Connect(TouchEnded)
O objeto de entrada de toque é o mesmo objeto de entrada ao longo da vida do toque.Então comparar InputObjects quando eles são objetos de toque é válido para determinar se é o mesmo dedo.
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Uma instância InputObject que contém informações sobre a entrada do usuário.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.
In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.
In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.
local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end
TouchLongPress
Dispedido quando um usuário mantém pelo menos um dedo por um curto período de tempo na mesma posição na tela de um dispositivo TouchEnabled.
Este evento pode ser usado para determinar quando um usuário mantém o dedo pressionado em um in-game GuiObject ou elemento.
O exemplo abaixo imprime o state da pressão longa quando o usuário segura pelo menos um dedo por um curto período de tempo na mesma posição na tela.Estados possíveis incluem: Começar , Mudar , Finalizar , Cancelar e Nenhum .
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)
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled .
Pode ser emparelhado com UserInputService.TouchStarted e UserInputService.TouchEnded para determinar quando um usuário começa e para de tocar na tela.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Um conjunto de Vector2 objetos, indicando a posição dos dedos envolvidos no gesto.
O Enum.UserInputState da gesta.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.
In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.
In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.
local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end
TouchMoved
Dispara quando um usuário move o dedo em um dispositivo TouchEnabled , como um tablet ou smartphone.
Este evento é útil para rastrear se um usuário está movendo o dedo na tela, bem como onde o usuário está movendo o dedo.
O código abaixo mostra o toque se movendo de sua posição anterior para uma nova posição em um dispositivo TouchEnabled .Observe que o InputObject.Position no parâmetro touch passado é um Vector3, mas inclui apenas X e Y coordenadas; Z é sempre 0.
local UserInputService = game:GetService("UserInputService")
function onTouchMoved(touch, gameProcessedEvent)
local oldPosition = touch.Position - touch.Delta
print("Touch moved from " .. tostring(oldPosition) .. " to " .. tostring(touch.Position))
end
UserInputService.TouchMoved:Connect(onTouchMoved)
Empareie este evento com UserInputService.TouchStarted e UserInputService.TouchEnded para determinar quando um usuário começa a tocar a tela, como seu dedo se move enquanto a toca e quando ele para de tocar a tela.
Para verificar se o dispositivo de um usuário suporta toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled .
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Uma instância InputObject que contém informações sobre a entrada do usuário.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.
In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.
In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.
local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end
TouchPan
O evento TouchPan dispara quando um usuário arrasta pelo menos um dedo em um dispositivo TouchEnabled.
Este evento pode ser usado para determinar quando um usuário desliza o dedo na tela de um dispositivo TouchEnabled - como para girar o Camera em um script de câmera personalizado.
O trecho a seguir imprime "Velocidade de toque" seguido pela velocidade do toque do usuário quando o usuário arrasta seu dedo na tela.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
print("Speed of touch drag: " .. tostring(velocity))
end)
Dê uma olhada em outra função útil UserInputService aqui UserInputService.TouchRotate.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Um conjunto de Vector2 objetos, indicando as posições dos toques (por exemplo, dedos) envolvidos no gesto.
O tamanho do gesto da panela de início a fim (em pixels).
A velocidade do gesto da panela (em pixels) por segundo.
O Enum.UserInputState da gesta.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.
The script is broken into two parts:
- Mobile camera events, which rely on touch events
- Non-mobile camera events, which rely on keyboard input and tracking the user's movement
First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.
Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.
The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.
All of the parts discussed above are combined and shown in the code sample below.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end
TouchPinch
Disparado quando um usuário coloca e move dois dedos na tela de um dispositivo TouchEnabled.
Por instância, o trecho a seguir imprime quanto a escala de zoom da câmera mudou desde o início do toque.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPinch:Connect(function(touchPositions, scale, velocity, state, gameProcessedEvent)
print("Scale difference since beginning of pinch: " .. tostring(scale))
end)
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco.Por exemplo, as entradas não serão capturadas quando a janela for minimizada.Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Um conjunto de Vector2s , indicando a posição da tela, em pixels, dos dedos envolvidos no gesto de pinça.
A magnitude do aperto de começo a fim (em pixels) dividida pelas posições de pincel iniciais.
A velocidade do gesto de pinça (em pixels) por segundo.
O Enum.UserInputState da gesta.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.
The script is broken into two parts:
- Mobile camera events, which rely on touch events
- Non-mobile camera events, which rely on keyboard input and tracking the user's movement
First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.
Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.
The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.
All of the parts discussed above are combined and shown in the code sample below.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end
TouchRotate
O evento TouchRotate é acionado quando um usuário gira dois dedos em um dispositivo TouchEnabled.
Por exemplo, o seguinte código imprime quanto a câmera girou desde o início da rotação de toque.
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchRotate:Connect(function(touchPositions, rotation, velocity, state, gameProcessedEvent)
print("Camera has rotated " .. tostring(rotation) .. " degrees!")
end)
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Os scripts principais que controlam a câmera do usuário em um dispositivo móvel usam código que funciona de forma semelhante a este evento.A melhor prática para este evento é usá-lo ao criar um sistema de câmera móvel para substituir os scripts padrão do núcleo.
Veja também:
Parâmetros
O número de grau que o gesto girou desde o início do gesto.
A mudança na rotação (em graus) dividida pela duração da mudança (em segundos).
O Enum.UserInputState da gesta.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
By default, Roblox relies on a LocalScript to control the user's camera. However, this script can be overridden with a custom CameraScript. The example below demonstrates how to create a custom script to control the user's camera using many of the UserInputService events.
The script is broken into two parts:
- Mobile camera events, which rely on touch events
- Non-mobile camera events, which rely on keyboard input and tracking the user's movement
First, the camera script needs utility functions to setup the camera and set its Camera.CameraType to Scriptable so that the script can control the camera. It also needs a function to update the camera when it moves, rotates, and zooms.
Using touch events allows us to track user input as they interact with the touchscreen on their mobile device. These events allow us to handle camera movement, rotation, and zoom.
The second half of the code sample adds camera support for players on desktop devices. When input begans, the function Input() checks that the state of the input is Enum.UserInputState.Begin to ignore all keypress inputs other than when the user first presses a key down. When the user presses I and O the camera zooms in and out. When the presses down and moves their left mouse button, the script locks the player's mouse by changing the UserInputService.MouseBehavior property. The camera rotates according to the mouse's change in screen position. When the player moves their character, the camera moves with them.
All of the parts discussed above are combined and shown in the code sample below.
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local camera = workspace.CurrentCamera
local player = Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local torso = character:WaitForChild("HumanoidRootPart")
local playerPosition = torso.Position
local default_CameraPosition = torso.Position
local default_CameraRotation = Vector2.new(0, math.rad(-60))
local default_CameraZoom = 15
local cameraPosition = default_CameraPosition
local cameraRotation = default_CameraRotation
local cameraZoom = default_CameraZoom
local cameraZoomBounds = nil -- {10,200}
local cameraRotateSpeed = 10
local cameraMouseRotateSpeed = 0.25
local cameraTouchRotateSpeed = 10
local function SetCameraMode()
camera.CameraType = "Scriptable"
camera.FieldOfView = 80
camera.CameraSubject = nil
end
local function UpdateCamera()
SetCameraMode()
local cameraRotationCFrame = CFrame.Angles(0, cameraRotation.X, 0) * CFrame.Angles(cameraRotation.Y, 0, 0)
camera.CFrame = cameraRotationCFrame + cameraPosition + cameraRotationCFrame * Vector3.new(0, 0, cameraZoom)
camera.Focus = camera.CFrame - Vector3.new(0, camera.CFrame.p.Y, 0)
end
local lastTouchTranslation = nil
local function TouchMove(_touchPositions, totalTranslation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = totalTranslation - lastTouchTranslation
cameraPosition = cameraPosition + Vector3.new(difference.X, 0, difference.Y)
UpdateCamera()
end
lastTouchTranslation = totalTranslation
end
local lastTouchRotation = nil
local function TouchRotate(_touchPositions, rotation, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = rotation - lastTouchRotation
cameraRotation = cameraRotation
+ Vector2.new(-difference, 0) * math.rad(cameraTouchRotateSpeed * cameraRotateSpeed)
UpdateCamera()
end
lastTouchRotation = rotation
end
local lastTouchScale = nil
local function TouchZoom(_touchPositions, scale, _velocity, state)
if state == Enum.UserInputState.Change or state == Enum.UserInputState.End then
local difference = scale - lastTouchScale
cameraZoom = cameraZoom * (1 + difference)
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
lastTouchScale = scale
end
local function Input(inputObject)
if inputObject.UserInputType == Enum.UserInputType.Keyboard then
if inputObject.UserInputState == Enum.UserInputState.Begin then
-- (I) Zoom In
if inputObject.KeyCode == Enum.KeyCode.I then
cameraZoom = cameraZoom - 15
elseif inputObject.KeyCode == Enum.KeyCode.O then
cameraZoom = cameraZoom + 15
end
-- (O) Zoom Out
if cameraZoomBounds ~= nil then
cameraZoom = math.min(math.max(cameraZoom, cameraZoomBounds[1]), cameraZoomBounds[2])
else
cameraZoom = math.max(cameraZoom, 0)
end
UpdateCamera()
end
end
local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
if pressed then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
local rotation = UserInputService:GetMouseDelta()
cameraRotation = cameraRotation + rotation * math.rad(cameraMouseRotateSpeed)
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function PlayerChanged()
local movement = torso.Position - playerPosition
cameraPosition = cameraPosition + movement
playerPosition = torso.Position
UpdateCamera()
end
-- Determine whether the user is on a mobile device
if UserInputService.TouchEnabled then
-- The user is on a mobile device, use Touch events
UserInputService.TouchPan:Connect(TouchMove)
UserInputService.TouchRotate:Connect(TouchRotate)
UserInputService.TouchPinch:Connect(TouchZoom)
else
-- The user is not on a mobile device use Input events
UserInputService.InputBegan:Connect(Input)
UserInputService.InputChanged:Connect(Input)
UserInputService.InputEnded:Connect(Input)
-- Camera controlled by player movement
task.wait(2)
RunService:BindToRenderStep("PlayerChanged", Enum.RenderPriority.Camera.Value - 1, PlayerChanged)
end
TouchStarted
O evento TouchStarted é acionado quando um usuário coloca o dedo em um dispositivo TouchEnabled, começando a entrada de toque com o dispositivo.
Este evento pode ser usado para determinar quando um usuário começa a tocar a tela do seu dispositivo.Pode ser emparelhado com UserInputService.TouchEnded para determinar quando um usuário começa e para de tocar na tela.
O objeto de entrada de toque é o mesmo objeto de entrada ao longo da vida do toque.Então comparar InputObjects quando eles são objetos de toque é válido para determinar se é o mesmo dedo.
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Uma instância InputObject que contém informações sobre a entrada do usuário.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
This example demonstrates how to use touch input events to drag a GUI element while a player touches and drags across their screen.
The touch InputObject is the same input object throughout the lifetime of the touch. So comparing input objects when they are touch objects is valid to determine if it is the same touch as the input starts, changes, and ends.
The example starts tracking a drag once the touch is registered by the TouchStarted() event. It continues to update as that touch moves, tracking its position relative to start position to move a GUI until a TouchEvent event fires for that touch.
local UserInputService = game:GetService("UserInputService")
local dragging
local dragInput
local dragStart
local startPos
local gui = script.Parent
local function touchStarted(input, _gameProcessed)
if not dragging then
dragging = true
dragInput = input
dragStart = input.Position
startPos = gui.Position
end
end
local function update(input, _gameProcessed)
if input == dragInput and dragging then
local delta = input.Position - dragStart
gui.Position =
UDim2.new(startPos.X.Scale, startPos.X.Offset + delta.X, startPos.Y.Scale, startPos.Y.Offset + delta.Y)
end
end
local function touchEnded(input, _gameProcessed)
if input == dragInput then
dragging = false
end
end
UserInputService.TouchStarted:Connect(touchStarted)
UserInputService.TouchMoved:Connect(update)
UserInputService.TouchEnded:Connect(touchEnded)
TouchSwipe
O evento TouchSwipe ocorre quando um usuário desliza seus dedos em um dispositivo TouchEnabled.
Este evento pode ser usado para determinar quando um usuário desliza seus dedos na tela de seu dispositivo e a direção que o usuário deslizou.
Para um rastreamento mais preciso do movimento de entrada de toque, use usando UserInputService.TouchMoved
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Um Enum.SwipeDirection , indicando a direção que o usuário deslizou.
Número de toques (por exemplo, dedos) envolvidos no gesto.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The example below demonstrates the TouchSwipe() event by tweening a GuiObject|GUI element's position 100 pixels in the direction of the swipe according to the value of the swipeDirection argument.
In order for this example to work as expected, it must be placed in a LocalScript that is parented to the gui being swiped.
local UserInputService = game:GetService("UserInputService")
local gui = script.Parent
local swipePositionY = gui.Position.Y.Offset
local swipePositionX = gui.Position.X.Offset
local camera = workspace.CurrentCamera
local maxY = camera.ViewportSize.Y - gui.Size.Y.Offset
local maxX = camera.ViewportSize.X - gui.Size.X.Offset
local function TouchSwipe(swipeDirection, _numberOfTouches, _gameProcessedEvent)
if swipeDirection == Enum.SwipeDirection.Up then
swipePositionY = math.max(swipePositionY - 200, 0)
elseif swipeDirection == Enum.SwipeDirection.Down then
swipePositionY = math.min(swipePositionY + 200, maxY)
elseif swipeDirection == Enum.SwipeDirection.Left then
swipePositionX = math.max(swipePositionX - 200, 0)
elseif swipeDirection == Enum.SwipeDirection.Right then
swipePositionX = math.min(swipePositionX + 200, maxX)
end
gui:TweenPosition(UDim2.new(0, swipePositionX, 0, swipePositionY), "Out", "Quad", 0.25, true)
end
UserInputService.TouchSwipe:Connect(TouchSwipe)
TouchTap
O evento TouchTap é acionado quando o usuário toca/toca no dedo na tela em um dispositivo TouchEnabled.
Este evento será disparado independentemente de se o usuário toca/toca no mundo do jogo ou em um elemento GuiObject.Se você estiver procurando por um evento que só dispara quando o usuário toca/toca no mundo do jogo, use UserInputService.TouchTapInWorld.
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Parâmetros
Um conjunto de Vector2 objetos, indicando a posição dos dedos envolvidos no gesto de toque.
Indica se o motor do jogo observou internamente esse input e agiu sobre ele.Em geral, isso se refere ao processamento de UI, então se um botão foi tocado ou clicado a partir desta entrada, gameProcessedEvent seria true.Isso também é verdade para eventos de entrada conectados via ContextActionService .
Amostras de código
The code sample below demonstrates the difference between a TouchTap() and TouchLongPress() by creating a GuiObject|GUI Frame that appears when user touches the screen of their device and disappears when the Class.UserInputEvent.TouchEnded|touch ends. When the long press event fires, the GUI doubles in size. Also, the GUI moves to stay centered under the user's finger when the player moves their finger.
In order for the TouchLongPress() to fire, the user touch the screen and hold their finger still for a short period of time. Once the touch moves, the long press event will not fire.
In order for the example to work as expected, it should be placed in a LocalScript that is parented to a ScreenGui.
local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end
TouchTapInWorld
O evento TouchTapInWorld é acionado quando o usuário toca/clica com o dedo na tela em um dispositivo TouchEnabled.Ele é disparado quando o usuário clica no mundo do jogo.
Este evento pode ser usado para determinar quando um usuário toca na tela e não toca em um elemento GuiObject.Se o usuário clicar em um elemento de GUI, UserInputService.TouchTap disparará em vez de TouchTapInWorld.
Para verificar se o dispositivo de um usuário está habilitado para toque e que eventos de toque serão Iniciar / executar, veja UserInputService.TouchEnabled.
Este evento só é disparado quando a janela do cliente Roblox está em foco. Por exemplo, as entradas não serão capturadas quando a janela for minimizada.
Como só dispara localmente, só pode ser usado em um LocalScript .
Veja também:
Parâmetros
Se o usuário clicou em um elemento de GUI.
Amostras de código
This example uses the Vector2 position passed by TouchTapInWorld() to find the Vector3 world position the user tapped. Then, the code spawns an anchored BasePart|Part at the world position.
In order to calculate the Vector3 world position using the viewport position, this example generates a Ray called unitRay originating from position using the ViewportPointToRay() function. Then, since ViewportPointToRay() creates a unit ray that is only 1 stud long, the example uses it to create a longer ray that is length studs long. Using FindPartOnRay(), the code determines where the ray first intersects a part in the world - the Vector3 world position that the user tapped.
Note that the code sample will not spawn a part if the user touches on the screen over an empty skybox. The touch must be on a part for FindPartOnRay() to return a Vector3 position.
local UserInputService = game:GetService("UserInputService")
local camera = workspace.CurrentCamera
local LENGTH = 500
local function createPart(position, processedByUI)
-- Do not create a part if the player clicked on a GUI/UI element
if processedByUI then
return
end
-- Get Vector3 world position from the Vector2 viewport position
local unitRay = camera:ViewportPointToRay(position.X, position.Y)
local ray = Ray.new(unitRay.Origin, unitRay.Direction * LENGTH)
local hitPart, worldPosition = workspace:FindPartOnRay(ray)
-- Create a new part at the world position if the player clicked on a part
-- Do not create a new part if player clicks on empty skybox
if hitPart then
local part = Instance.new("Part")
part.Parent = workspace
part.Anchored = true
part.Size = Vector3.new(1, 1, 1)
part.Position = worldPosition
end
end
UserInputService.TouchTapInWorld:Connect(createPart)
WindowFocusReleased
O evento WindowFocusReleased UserInputService é acionado quando a janela do cliente Roblox perde o foco - geralmente quando o cliente Roblox é minimizado pelo usuário.
Por exemplo, o código abaixo imprime “Foco da janela liberado” sempre que o cliente Roblox perde o foco.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocusReleased:Connect(function()
print("Window focus released")
end)
Este evento pode ser usado ao lado de UserInputService.WindowFocused para rastrear se o cliente Roblox está ativamente focado na tela de um usuário.
Como só dispara localmente, só pode ser usado em um LocalScript .
Amostras de código
This example fires a RemoveEvent to the server name AfkEvent when the LocalPlayer's client gains or loses focus.
The purpose of this code sample is to fire a server-side event to indicate when the player is AFK. This is indicated by spawning a ForceField around the player when the client loses focus and destroying the forcefield when the client gains focus.
In order for this example to work as expected, the code labelled LocalScript must be placed in a LocalScript and the code labelled Script must be placed in a Script. This sample is a Script which should be run in conjunction with the LocalScript code sample: Window Focus AFK Script (LocalScript)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = Instance.new("RemoteEvent")
afkEvent.Name = "AfkEvent"
afkEvent.Parent = ReplicatedStorage
local function setAfk(player, afk)
if afk then
local forcefield = Instance.new("ForceField")
forcefield.Parent = player.Character
else
local forcefield = player.Character:FindFirstChildOfClass("ForceField")
if forcefield then
forcefield:Destroy()
end
end
end
afkEvent.OnServerEvent:Connect(setAfk)
This sample is a LocalScript which should be run in conjunction with the Script code sample: Window Focus AFK Script (Script)
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = ReplicatedStorage:WaitForChild("AfkEvent")
local function focusGained()
afkEvent:FireServer(false)
end
local function focusReleased()
afkEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)
WindowFocused
O evento WindowFocused UserInputService ocorre quando a janela do cliente Roblox ganha foco - geralmente quando o cliente Roblox é maximizado/ativamente aberto na tela do usuário.
Por exemplo, o código abaixo imprime “Foco na janela” sempre que o cliente Roblox ganha foco.
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocused:Connect(function()
print("Window focused")
end)
Este evento pode ser usado ao lado de UserInputService.WindowFocusReleased para rastrear se o cliente Roblox está ativamente focado na tela de um usuário.
Como este evento só é disparado localmente, ele só pode ser usado em um LocalScript .
Amostras de código
This example fires a RemoveEvent to the server name AfkEvent when the LocalPlayer's client gains or loses focus.
The purpose of this code sample is to fire a server-side event to indicate when the player is AFK. This is indicated by spawning a ForceField around the player when the client loses focus and destroying the forcefield when the client gains focus.
In order for this example to work as expected, the code labelled LocalScript must be placed in a LocalScript and the code labelled Script must be placed in a Script. This sample is a Script which should be run in conjunction with the LocalScript code sample: Window Focus AFK Script (LocalScript)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = Instance.new("RemoteEvent")
afkEvent.Name = "AfkEvent"
afkEvent.Parent = ReplicatedStorage
local function setAfk(player, afk)
if afk then
local forcefield = Instance.new("ForceField")
forcefield.Parent = player.Character
else
local forcefield = player.Character:FindFirstChildOfClass("ForceField")
if forcefield then
forcefield:Destroy()
end
end
end
afkEvent.OnServerEvent:Connect(setAfk)
This sample is a LocalScript which should be run in conjunction with the Script code sample: Window Focus AFK Script (Script)
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = ReplicatedStorage:WaitForChild("AfkEvent")
local function focusGained()
afkEvent:FireServer(false)
end
local function focusReleased()
afkEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)