UserInputService

사용되지 않는 항목 표시

*이 콘텐츠는 AI(베타)를 사용해 번역되었으며, 오류가 있을 수 있습니다. 이 페이지를 영어로 보려면 여기를 클릭하세요.

만들 수 없음
서비스
복제되지 않음

UserInputService는 사용자 기기사용할 수 있는 다양한 입력 유형을 감지하고 캡처하는 서비스입니다.

이 서비스의 주요 목적은 게임 패드, 터치 화면 및 키보드와 같은 다양한 입력 유형과 경험이 협력하도록 하는 것입니다. LocalScript 는 장치에 따라 다양한 작업을 수행하고, 결과적으로 최상의 경험을 제공합니다.

이 서비스의 일부 사용 사례는 사용자가 GUI, 도구 및 기타 게임 인스턴스와 상호 작용할 때 사용자 입력을 감지하는 것입니다. 사용자 입력을 감지하려면 서비스는 서비스 이벤트를 검색해야 합니다. 예를

이 서비스는 클라이언트 사이트 전용이므로 클라이언트에서만 사용되도록 하려면 LocalScript 또는 ModuleScript 필요한 경우에만 작동합니다. As UserInputService 는 클라이언트 사이트 전용이므로 게임 내의 사용자만 자신의 입력을 감지할 수 있으며 다른 사용

또한 ContextActionService 를 참조하십시오, 이는 함수를 여러 사용자 입력에 바인딩하는 서비스입니다.

코드 샘플

UserInputService

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

요약

속성

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자 장치에 가속 센서가 있는지 여부를 설명합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자가 사용하는 장치에 게임 패드가 사용 가능한지 여부를 설명합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자 장치에 자이로스코프가 있는지 여부를 설명합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자 장치에 키보드가 있는지 여부를 설명합니다.

  • 사용자의 마우스를 자유롭게 이동할 수 있는지 또는 잠겨 있는지 결정합니다.

  • 복제되지 않음
    병렬 읽기

    사용자의 Mouse 의 델타 출력을 조정합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자 장치에 마우스가 있는지 여부를 설명합니다.

  • MouseIcon:ContentId
    병렬 읽기

    사용자 마우스 아이콘으로 사용된 이미지의 콘텐츠 ID.

  • 병렬 읽기

    Class.Mouse 아이콘이 표시되는지 여부를 결정합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    화면 키보드의 위치를 결정합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    화면 키보드 크기를 결정합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자 화면에 현재 온-스크린 키보드가 표시되는지 여부를 설명합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자의 현재 장치에 터치 화면이 있는지 여부를 설명합니다.

  • 읽기 전용
    복제되지 않음
    병렬 읽기

    사용자가 가상 현실 헤드셋을 사용하는지 여부를 나타냅니다.

메서드

이벤트

속성

AccelerometerEnabled

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자 장치에 가속도 센서가 있는지 여부를 설명합니다.

가속도 (속도 변경)를 측정하는 대부분의 모바일 장치에서 가속도 센서는 구성 요소입니다.

예를 들어 다음 코드 샘플은 사용자 장치에 가속도 센서가 있는지 여부를 확인하는 방법을 보여줍니다.


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

장치에 가속 센서가 있으면 장치의 가속을 사용하여 UserInputService:GetDeviceAcceleration() 함수나 이벤트를 사용하여 현재 가속을 얻을 수 있습니다. 기기가속이 UserInputService.DeviceAccelerationChanged 이벤트를 사용하여 변경되면 트랙을 사용하여 현재 가속을 얻을 수 있습니다

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

코드 샘플

Move a Ball using the Accelerometer

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

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

GamepadEnabled

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자가 사용하는 장치에 게임 패드가 사용 가능한지 여부를 설명합니다. 게임 패드가 사용 가능하면 UserInputService:GetConnectedGamepads()를 사용하여 연결된 게임 패드의 목록을 검색할 수 있습니다.

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.

코드 샘플

How to Set the Active Gamepad for Input

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

GyroscopeEnabled

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자 장치에 자이로스코프가 있는지 여부를 설명합니다.

자이로스코프는 방향과 회전 속도를 감지하는 대부분의 모바일 장치에서 찾을 수 있는 구성 요소입니다.

사용자의 장치에 가속도 센서가 있으면 UserInputService:GetDeviceRotation() 함수와 UserInputService.DeviceRotationChanged 이벤트를 사용하여 게임에 통합할 수 있습니다.


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

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

코드 샘플

Create a Gyroscopic Camera

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

KeyboardEnabled

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자 장치에 키보드가 있는지 여부를 설명합니다. 이 속성은 사용자 장치에 키보드가 있는 경우 true이고, 사용자 장치에 키보드가 없는 경우 false입니다.

사용자가 사용 가능한 키보드가 있는지 여부를 결정하는 데 사용할 수 있습니다. - 이 경우 키보드 입력을 확인하려면 UserInputService:IsKeyDown() 또는 UserInputService:GetKeysPressed()를 사용할 수 있습니다.

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

코드 샘플

Check if Keyboard is Enabled

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

MouseBehavior

병렬 읽기

이 속성은 사용자의 마우스 동작을 Enum.MouseBehavior 열에 설정합니다. 기본 값은 Enum.MouseBehavior.Default입니다.

다음 값 세 개로 설정할 수 있습니다.

  1. 기본 : 마우스는 사용자 화면 주위를 자유롭게 이동합니다.
  2. 잠금 센터 : 마우스가 잠겨 있으며 사용자 화면의 중심에서 이동할 수 없습니다.
  3. 현재 위치 잠금 잠금CurrentPosition lockCurrentPosition : 마우스가 잠겨 있으며, 잠긴 상태의 사용자 화면에서 현재 위치를 잠긴 상태로 변경할 수 없습니다.

이 속성의 값은 이벤트 추적 마우스 이동 민감도에 영향을 주지 않습니다. 예를 들어, GetMouseDelta는 마우스가 잠겨 있든 여부에 관계없이 동일한 Vector2 화면 위치를 반환합니다. 결

이 속성은 GuiButtonModal 이 활성화되어 있는 경우에만 GuiButton.Visible 이 아님에 따라 재정의됩니다.

참고로, 마우스가 잠겨 있으면 UserInputService.InputChanged 는 플레이어가 마우스를 이동할 때 여전히 작동하고 마우스가 이동하려는 델타를 패스합니다. 또한, 플레이어가 게임에서 킥당하면 마우스가 강제로 잠금 해제됩니다.

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

코드 샘플

Create a Binoculars Script

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

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

MouseDeltaSensitivity

복제되지 않음
병렬 읽기

이 속성은 Mouse의 사용자 민감도를 결정합니다.

민감도는 물리 마우스의 이동이 게임 내 마우스 이동으로 얼마나 번역되는지 결정합니다. 이를 사용하여 게임 내 이벤트 추적 마우스 이동, 예를 들어 GetMouseDelta ,의 민감도를 조정할 수 있습니다.

이 속성은 마우스 아이콘의 이동에 영향을 주지 않습니다. 또한 클라이언트의 설정 메뉴에 있는 카메라 민감도 설정에도 영향을 주지 않습니다. 이 설정은 이벤트 추적 마우스 이동 민감도를 조정하는 클라이언트의 설정 탭에서도 조정됩니다.

이 속성의 최대 값은 10이고 최소 값은 0입니다. 낮은 값은 낮은 민감도에 해당하고 높은 값은 높은 민감도에 해당합니다.

민감도가 0인 경우 마우스 이동을 추적하는 이벤트는 여전히 발생하지만 모든 변수 및 속성이 마우스 위치의 변경을 나타내는 Vector2.new() 또는 Vector3.new()

코드 샘플

Create a Binoculars Script

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

MouseEnabled

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자 장치에 마우스가 사용 가능한지 여부를 설명합니다. 이 속성은 사용자 장치에 마우스가 사용 가능한 경우 true이고, 사용 가능한 마우스가 없는 경우 false입니다.


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

이 중 UserInputService 마우스 함수를 사용하기 전에 확인하는 것이 좋습니다.

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.

코드 샘플

Create a Binoculars Script

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

MouseIcon

ContentId
병렬 읽기

마우스 아이콘 속성은 포인터로 사용할 이미지를 결정합니다. 비워 두면 기본 화살표가 사용됩니다. Class.ImageButton, ImageButton, TextButton 또는 2>Class.ProximityPrompt2>와 같은 특정 UI 개체

커서를 완전히 숨기려면 투명한 이미지를 사용하지 마십시오. 대신 Class.UserInputService.MouseIconEnabled를 참조하십시오.

코드 샘플

UserInputService.MouseIcon

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

MouseIconEnabled

병렬 읽기

이 속성은 Mouse 아이콘이 표시되는지 여부를 결정합니다. true 마우스의 아이콘이 표시되면, false 그렇지 않으면.

예를 들어 아래 코드 란은 마우스의 아이콘을 숨깁니다.


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

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

코드 샘플

Hide Mouse During Keyboard Input

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

OnScreenKeyboardPosition

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 화면 키보드의 위치를 픽셀로 설명합니다. 키보드의 위치는 보이지 않을 때 Vector2.new(0, 0)입니다.

Class.UserInputService 는 클라이언트 사이드만 사용할 수 있으므로, 이 속성은 LocalScript 또는 Script 에서만 사용할 수 있습니다. 1>Class.BaseScript.RunContext|RunContext1> 를 설정하여 4>Enums.RunContext.Client4> 에 대해

또한 OnScreenKeyboardVisibleOnScreenKeyboardSize 을 참조하십시오.

코드 샘플

UserInputService.OnScreenKeyboardPosition

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

OnScreenKeyboardSize

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 화면 키보드의 크기를 픽셀로 설명합니다. 키보드의 크기는 보이지 않을 때 Vector2.new(0, 0)입니다.

Class.UserInputService 는 클라이언트 사이드만 사용할 수 있으므로, 이 속성은 LocalScript 또는 Script 에서만 사용할 수 있습니다. 1>Class.BaseScript.RunContext|RunContext1> 를 설정하여 4>Enums.RunContext.Client4> 에 대해

또한 OnScreenKeyboardVisibleOnScreenKeyboardPosition 을 참조하십시오.

OnScreenKeyboardVisible

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자 화면에 현재 키보드가 표시되는지 여부를 설명합니다.

Class.UserInputService 는 클라이언트 사이드만 사용할 수 있으므로, 이 속성은 LocalScript 또는 Script 에서만 사용할 수 있습니다. 1>Class.BaseScript.RunContext|RunContext1> 를 설정하여 4>Enums.RunContext.Client4> 에 대해

또한 OnScreenKeyboardSizeOnScreenKeyboardPosition 을 참조하십시오.

TouchEnabled

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자의 현재 장치에 터치 화면이 있는지 여부를 설명합니다.

속성은 사용자 기기터치 화면이 있는지 여부를 결정하기 위해 사용되며, 따라서 터치 이벤트가 발생하는지 여부를 결정합니다. 터치Enabled가 사용자 입력 서비스(예: UserInputService.TouchStartedUserInputService.TouchEnded를 사용하면 사용자가

아래에 있는 코드 캐럿은 사용자 장치에 터치 화면이 있는지 여부를 인쇄합니다.


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

또한 참조하십시오.

코드 샘플

Create a Custom CameraScript

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

VREnabled

읽기 전용
복제되지 않음
병렬 읽기

이 속성은 사용자가 가상 현실(VR) 기기사용하는지 여부를 설명합니다.

VR 장치가 활성화되면, 위치 및 이동을 조정하기 위해 함수를 사용하여 UserInputService:GetUserCFrame() 와 같은 것들과 상호 작용할 수 있습니다. 또한, UserInputService.UserCFrameChanged 이벤트를 사용하여 VR 장치의 이동을 반응할 수도 있습니다.


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

Class.UserInputService 는 클라이언트 사이드 전용이므로 이 속성은 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.

코드 샘플

VR Head Tracking

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

메서드

GamepadSupports

이 함수는 지정한 Enum.UserInputType 게임 패드가 지정한 Enum.KeyCode와 일치하는 버튼을 지원하는지 여부를 반환합니다. 이 함수는 유효한 게임 패드 입력을 결정하는 데 사용됩니다.

어떤 게임 패드에 연결된 Enum.UserInputType 게임 패드인지 결정하려면 UserInputService:GetConnectedGamepads() 를 사용하십시오.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.

매개 변수

gamepadNum: Enum.UserInputType

게임 패드의 Enum.UserInputType입니다.

gamepadKeyCode: Enum.KeyCode

문제의 버튼의 Enum.KeyCode입니다.


반환

지정된 게임 패드가 지정된 Enum.KeyCode와 일치하는 버튼을 지원하는지 여부.

코드 샘플

Binding Functions to Gamepad Controls

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

GetConnectedGamepads

이 함수는 현재 연결된 게임 패드의 배열을 반환합니다. 게임 패드가 연결되지 않으면 이 배열은 비어 있습니다. 또한, 게임 패드가 연결되지 않으면 키보드 개체가 아닌 게임 패드 개체만 반환합니다. 예를 인스턴스, 이 이벤트는 연결된 Gamepad1 개체를 반환하지만 키보드 개체는 반환하

예를 들어 다음 코드 덩어리는 연결된 게임 패드를 검색하고 해당 게임 패드를 변수 connectedGamepads 에 저장합니다.


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

특정 게임 패드가 연결되어 있는지 확인하려면 UserInputService:GetGamepadConnected() 를 사용합니다.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.


반환

사용자 기기연결된 게임 패드와 일치하는 UserInputTypes 배열.

코드 샘플

How to Set the Active Gamepad for Input

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

GetDeviceAcceleration

GetDeviceAcceleration 함수는 사용자 기기현재 가속을 결정합니다. 기기현재 가속을 설명하는 InputObject를 반환합니다.

이 작업이 작동하려면 사용자의 장치에 가속 센서가 활성화되어 있어야 합니다. 사용자의 장치에 가속 센서가 활성화되어 있는지 확인하려면 UserInputService.AccelerometerEnabled 속성을 확인할 수 있습니다.

사용자의 기기가속이 대신 변경된 경우 UserInputService.DeviceAccelerationChanged 이벤트를 사용하여 추적할 수 있습니다.

로컬에서만 실행되므로 LocalScript 에만 사용할 수 있습니다.


반환

코드 샘플

Print Device Acceleration

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

GetDeviceGravity

이 함수는 기기현재 중력 벡터를 설명하는 InputObject를 반환합니다.

중력 벡터는 기기방향이 실제 세계의 중력 힘과 비례하여 결정됩니다. 예를 인스턴스, 장치가 완벽하게 세로 있는 경우(초상화) 중력 벡터는 Datatype.Vector3|Vector3.new

이 함수는 사용자의 장치가 게임 내에서 중력에 영향을 주거나 공을 이동하는 등의 작업을 수행할 수 있게 하도록 사용할 수 있습니다.

장치에 장착된 자이로스콜 기능을 사용하는 플레이어만 중력을 추적합니다. - 예를 들어, 모바일 기기.

사용자의 장치에 장착된 자이로스코프가 있는지 확인하려면 UserInputService.GyroscopeEnabled 값을 확인하십시오. 장치에 장착된 자이로스코프가 있는 경우 UserInputService.DeviceGravityChanged 이벤트를 사용하여 사용자의 장치에서 중력 힘이 변경될 때를

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.


반환

코드 샘플

Moving Objects with the Gyroscope

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

GetDeviceRotation

이 함수는 InputObjectCFrame을 반환하고 기기현재 회전 벡터를 설명하는 Datatype.CFrame를 반환합니다.

이 메서드는 입력 개체에 대해 호출됩니다. 입력 개체의 위치 속성은 각 로컬 장치 축에 대한 총 회전을 추적하는 Enum.InputType.Gyroscope입니다.

장치 회전은 장치에 장착된 gyroscope 만 추적할 수 있습니다.

이 함수가 로컬에서 실행되므로 LocalScript 내에서만 사용할 수 있습니다.


반환

다음 속성을 포함하는 템플릿:

  1. 델타 속성은 마지막으로 발생한 회전 량을 설명합니다.
  2. CFrame은 기본 참조 프레임과 대비된 기기현재 회전 관점입니다.

코드 샘플

Print Device Rotation

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

GetFocusedTextBox

이 함수는 클라이언트가 현재 초점을 맞추고 있는 TextBox를 반환합니다. 사용자가 텍스트 상자를 수동으로 선택하거나 TextBox:CaptureFocus() 함수를 사용하여 선택을 강제할 수 있습니다. 텍스트 상자가 선택되지 않으면 이 함수는 nil를 반환합니다.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.


반환

코드 샘플

Ignore User Input When a TextBox Is Focused

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 jumpKey = Enum.KeyCode.J
local isJumping = false
local function InputBegan(input, _gameProcessedEvent)
local TextBoxFocused = UserInputService:GetFocusedTextBox()
-- Ignore input event if player is focusing on a TextBox
if TextBoxFocused then
return
end
-- Make player jump when user presses jumpKey Key on Keyboard
if input.UserInputType == Enum.UserInputType.Keyboard and input.KeyCode == jumpKey then
if not isJumping then
isJumping = true
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
end
end
local function StateChanged(_oldState, newState)
-- Prevent player from jumping again using jumpKey if already jumping
if newState == Enum.HumanoidStateType.Jumping then
isJumping = true
-- Allow player to jump again after landing
elseif newState == Enum.HumanoidStateType.Landed then
isJumping = false
end
end
UserInputService.InputBegan:Connect(InputBegan)
humanoid.StateChanged:Connect(StateChanged)

GetGamepadConnected

이 함수는 지정한 Enum.UserInputType 게임 패드가 클라이언트에 연결되어 있는지 여부를 반환합니다.

이 도구는 클라이언트 기기연결된 특정 게임 패드, 예를 들어 게임 패드1 이 연결되어 있는지 확인하는 데 사용할 수 있습니다.

연결된 모든 게임 패드 목록을 검색하려면 UserInputService:GetConnectedGamepads()를 사용하십시오.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.

매개 변수

gamepadNum: Enum.UserInputType

문제의 게임 패드의 Enum.UserInputType입니다.


반환

게임 패드가 Enum.UserInputType와 연결되어 있는지 여부.

코드 샘플

Check Whether a Gamepad is Connected

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

GetGamepadState

이 함수는 제공된 InputObjects 게임 패드의 모든 가능한 입력에 대해 Enum.UserInputType 배열을 반환합니다. 각 입력의 마지막 입력 상태를 나타냅니다.

연결된 게임 패드의 UserInputTypes 을 찾으려면 UserInputService:GetConnectedGamepads() 를 사용하십시오.

이 함수는 로컬에서만 실행되므로 LocalScript 에만 사용할 수 있습니다.

또한 참조하십시오.

매개 변수

gamepadNum: Enum.UserInputType

해당 게임 패드에 대응하는 Enum.UserInputType입니다.


반환

Class.InputObject|InputObjects 현재 상태를 나타내는 배열.

GetImageForKeyCode

ContentId

이 메서드는 요청한 Enum.KeyCode 를 가져와 현재 연결된 게임 패드 장치(Xbox, PlayStation 및 Windows)에 대해 연관된 이미지를 반환합니다(제한: Xbox 1 컨트롤러). 즉, 연결된 컨트롤러가 Xbox 컨트롤러인 경우 사용자

매개 변수

keyCode: Enum.KeyCode

연관된 이미지를 검색할 Enum.KeyCode 입니다.


반환

ContentId

반환된 이미지 자산 ID.

코드 샘플

UserInputService - Get Image For KeyCode

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

GetKeysPressed

이 함수는 현재 키가 누르고 있는 배열의 InputObjects 을 반환합니다.

이 배열을 반복하여 현재 누르고 있는 키를 결정하는 데 사용됩니다 InputObject.KeyCode 값.

특정 키가 누르고 있는지 확인하려면 UserInputService:IsKeyDown() 을 사용합니다.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.


반환

현재 키가 누르고 있는 배열의 InputObjects 입니다.

코드 샘플

Double Jump Key Combo

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

GetLastInputType

이 함수는 사용자의 가장 최근 입력과 관련된 '열거형.UserInputType'를 반환합니다.

예를 들어, 사용자의 이전 입력이 스페이스 바를 누르고 있었다면 Enum.UserInputType 반환 된 것은 키보드 였습니다.

사용자가 사용하는 마지막 UserInputService.LastInputTypeChanged 이벤트를 사용하여 사용자가 변경한 마지막 Enum.UserInputType를 추적할 수 있습니다.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.


반환

사용자의 가장 최근 입력과 관련된 Enum.UserInputType입니다.

코드 샘플

UserInputService:GetLastInputType

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

GetMouseButtonsPressed

이 함수는 현재 마우스 버튼이 누르고 있는 것에 해당하는 InputObjects 배열을 반환합니다.

이 함수에 의해 추적되는 마우스 버튼은 다음과 같습니다.


<tr>
<td>마우스 버튼1</td>
<td>왼쪽 마우스 버튼입니다.</td>
</tr>
<tr>
<td>마우스 버튼 2</td>
<td>오른쪽 마우스 버튼.</td>
</tr>
<tr>
<td>마우스 버튼3</td>
<td>중간 마우스 버튼.</td>
</tr>
이름설명

함수가 호출될 때 사용자가 아무 마우스 버튼을 눌러 내리지 않으면 빈 배열을 반환합니다.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.


반환

현재 마우스 버튼을 잠겨 있는 배열의 InputObjects 입니다.

코드 샘플

Check which MouseButtons are Pressed

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

GetMouseDelta

이 함수는 마지막 렌더링 프레임에서 플레이어의 Mouse 위치의 변경 내용을 픽셀 단위로 반환합니다. 이 함수는 Vector2 속성을 사용하여 마우스를 잠긴 경우에만

클라이언트의 설정에 따라 마우스의 민감도, UserInputService.MouseDeltaSensitivity , 결과에 영향을 미칠 수 있습니다.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.


반환

마우스의 이동 변경.

코드 샘플

Getting Mouse Delta

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

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

GetMouseLocation

이 함수는 플레이어의 Vector2의 현재 화면 위치를 나타내는 Mouse를 반환합니다. 이 함수는 상위 왼쪽 모서리에 대한 GUI의 인센트를 계산하지 않습니다.

마우스 포인터의 위치가 오프스크린인 경우 또는 플레이어의 장치에 마우스가 없는 경우 반환된 값은 결정되지 않습니다.

클라이언트 사이드 전용인 UserInputService 함수는 LocalScript 에서만 사용할 수 있습니다.


반환

마우스의 현재 화면 위치를 Vector2 표시합니다.

코드 샘플

Move GUI To Mouse Location

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

GetNavigationGamepads

이 함수는 GUI 탐색에 사용할 게임 패드 배열을 반환합니다. UserInputTypes 연결되고 활성화된 게임 패드 배열이 있습니다. 이 목록은 우선 순위가 내리는 순서로 정렬되므로 게임 패드에서 탐색 컨트롤이 있는 경우에만 반복할 수 있습니다.

연결된 게임 패드가 탐색 게임 패드인지 여부는 탐색 GUI를 제어하는 게임 패드(s)만 결정합니다. 이것은 탐색 컨트롤에 영향을 주지 않습니다.

Class.UserInputService 는 클라이언트 사이드 기능이므로 이 함수는 LocalScript 에서만 사용할 수 있습니다.

또한 참조하십시오.


반환

우선 순위가 내려진 순서로 GUI 탐색에 사용할 수 있는 UserInputTypes 배열.

GetStringForKeyCode

GetStringForKeyCode 는 사용자가 입력하려는 키를 나타내는 문자열을 반환하지만 키보드 레이아웃을 유지하는 데 필요한 키를 나타냅니다. 키 코드에 모드 변경기를 보유해야 하는 경우 이 함수는 키를 모드 변경기 대신 반환합니다. 예를 위해 아래에서 자세한 설명

Roblox에서 일반 키보드 레이아웃을 사용하는 경우 키 코드는 상당한 정보를 기반으로 맵


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

QWERTY 키보드의 예시


<tbody>
<tr>
<td><code>열거형 키 코드</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>열거형 키 코드.</code></td>
<td><code>2</code> 은 왜냐하면 <code>@</code>는 <kbd>Shift</kbd>로 입력되고 <kbd>2</kbd>는 2>입력 된2></td>
</tr>
</tbody>
키 코드값 반환

AZERTY 키보드의 예


<tbody>
<tr>
<td><code>열거형 키 코드</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>열거형 키 코드.</code></td>
<td><code>É</code></td>
</tr>
</tbody>
키 코드값 반환

게임 패드 사용

GetStringForKeyCode() 는 가장 최근에 연결된 게임 패드에 대해 Enum.KeyCode 의 문자열 매핑을 반환합니다. 연결된 컨트롤러가 지원되지 않으면 요청된 키 코드에 대해 기본 문자열 변환을 반환합니다.

다음 예시에서는 사용자 정의 자산을 ButtonA에 대해 맵하는 방법을 보여줍니다.


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

게임 패드 매핑

방향 패드 키 코드에는 기기따라 차이가 없습니다. Enum.KeyCode.ButtonSelect 는 일부 경우 PlayStation 맵을 사용하여 올바른 버튼을 표시합니다. 모든 사용자가 올바른 버튼을 볼 수 있도록 하려면 둘 다 PlayStation 맵을 사용하십시오.


<tbody>
<tr>
<td><code>열거형 키 코드 버튼</code></td>
<td><code>버튼 십자가</code></td>
<td><code>버튼A</code></td>
</tr>
<tr>
<td><code>enum.keycode.buttonb</code></td>
<td><code>버튼 원</code></td>
<td><code>버튼B</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td><code>버튼 스퀘어</code></td>
<td><code>버튼X</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼</code></td>
<td><code>버튼 트라이앤글</code></td>
<td><code>버튼Y</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼 L1</code></td>
<td><code>ButtonL1</code></td>
<td><code>ButtonLB</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼 L2</code></td>
<td><code>ButtonL2</code></td>
<td><code>버튼LT</code></td>
</tr>
<tr>
<td><code>Enum.KeyCode.ButtonL3</code></td>
<td><code>ButtonL3</code></td>
<td><code>ButtonLS</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼 R1</code></td>
<td><code>ButtonR1</code></td>
<td><code>버튼 RB</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼 R2</code></td>
<td><code>ButtonR2</code></td>
<td><code>버튼RT</code></td>
</tr>
<tr>
<td><code>enum.keycode.buttonr3</code></td>
<td><code>ButtonR3</code></td>
<td><code>버튼 RS</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼 시작</code></td>
<td><code>버튼 옵션</code></td>
<td><code>버튼 시작</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼 선택</code></td>
<td><code>ButtonTouchpad</code> 및 <code>ButtonShare</code></td>
<td><code>버튼 선택</code></td>
</tr>
</tbody>
키 코드PlayStation 반환 값Xbox 반환 값

키 코드에 대한 시스템 이미지

사용자 인터페이스에 있는 Enum.KeyCode 같은 이미지를 나타내는 것이 좋은 표시인 경우 ImageLabel 를 사용하는 것이 좋습니다. 그러나 이 경우 더 이상 권장되지 않습니다. Class.UserInputService:GetImageForKeyCode()


<tbody>
<tr>
<td><code>Enum.KeyCode.ButtonX</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxX.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxX.png</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxY.png" width="24">
</img>
</td>
<td><code>rbxasset://textures/ui/Controls/xboxY.png</code></td>
</tr>
<tr>
<td><code>열거형 키 코드 버튼</code></td>
<td>
<img src="../../../assets/scripting/controls/xboxA.png" width="24">