UserInputService
*このコンテンツは、ベータ版のAI(人工知能)を使用して翻訳されており、エラーが含まれている可能性があります。このページを英語で表示するには、 こちら をクリックしてください。
UserInputService は、ユーザーのデバイスで利用可能なさまざまな種類の入力を検出してキャプチャするサービスです。
このサービスの主目的は、ゲームパッド、タッチスクリーン、キーボードなどの多様な入力形式との協力を可能にすることです。それは、デバイスによって異なるアクションを実行する LocalScript を許可し、結果として最高のエンドユーザーエクスペリエンスを提供します。
このサービスの使用の一部には、GUI、ツール、その他のゲームインスタンスとの対話中にユーザーの入力を検出することが含まれます。ユーザーの入力を検出するには、サービスはサービスイベントを探す必要があります。たとえば、サービスは、ユーザーがモバイルデバイスの画面をタッチするときなどのイベントを検出でき、UserInputService.TouchStarted でゲームパッドのような Xbox コントローラーをデバイスに接続したり、UserInputService.GamepadConnected でデバイスにモバイルデバイスの画面を接続したりします。
このサービスはクライアント側のみであるため、LocalScript または ModuleScript によって必要な LocalScript でのみ機能します。ユーザーインプットサービスはクライアント側のみなので、ゲーム内のユーザーは自分の入力のみを検出できます - 他のユーザーの入力は検出できません。
参照してください ContextActionService , 複数のユーザー入力に機能をバインドできるサービス。
コードサンプル
-- 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 のデルタ (変更) 出力をスケールします。
ユーザーのデバイスにマウスが使用可能かどうかを説明します。
ユーザーマウスアイコンとして使用される画像のコンテンツID。
Mouse アイコンが表示されるかどうかを決定します。
画面上のキーボードの位置を決定します。
画面上のキーボードのサイズを決定します。
画面上のキーボードが現在ユーザーの画面に表示されているかどうかを説明します。
ユーザーの現在のデバイスにタッチスクリーンが利用可能かどうかを説明します。
ユーザーがバーチャルリアリティヘッドセットを使用しているかどうかを示します。
方法
指定された Enum.UserInputType ゲームパッドが、指定された Enum.KeyCode に対応するボタンをサポートしているかどうかを返します。
現在接続されているゲームパッドのアレイを返します Enum.UserInputType
デバイスの現在の加速を説明する InputObject を返します。
デバイス置の現在の重力ベクトルを説明する InputObject を返します。
デバイスの現在の回転ベクトルを説明する InputObject と CFrame を返し、装置の現在の回転ベクトルを説明します。
現在、クライアントが焦点を当てている TextBox を返します。
指定された Enum.UserInputType ''gamepadNum'' のゲームパッドが接続されているかどうかを返します。
指定されたゲームパッドのすべての利用可能な入力に対して、InputObjects の配列を返し、それぞれの入力の最後の入力状態を表示します。
リクエストされた Enum.KeyCode の画像を返します。
現在押されている に関連する配列を返します。
ユーザーの最新の入力に関連する Enum.UserInputType を返します。
現在押されているマウスボタンに対応する InputObjects のアレイを返します。
最後にレンダリングされたフレームで、プレイヤーの Mouse の位置の変更をピクセルで返します。マウスがロックされている場合にのみ機能します。
プレイヤーの現在の画面位置を返し、画面の左上隅に対して Mouse 相対します。
連結して優先順位の下降順でGUIナビゲーションに有効な gamepads のアレイを返します。
ユーザーが指定された Enum.KeyCode を入力するために押す必要のあるキーを表す文字列を返します。
返すのは、KeyCodes に関連付けられたゲームパッドにサポートされる配列の Enum.UserInputType 。
特定のゲームパッドで特定のボタンが押されているかどうかを決定します。
指定された key が現在押されているかどうかを返します。
指定された mouse button が現在押されているかどうかを返します。
指定された ゲームパッドがナビゲーションを制御することを許可されている場合、真を返します。
VR ヘッドセットの CFrame をユーザーが着用しているヘッドセットの現在の方向に中央化します。
指定された がナビゲーターを移動できるかどうかを設定します。
イベント
ユーザーが加速度センサーを持つデバイスを移動すると発射されます。Roblox ゲーム内で実世界のデバイスの移動を追跡するのに使用されます。
有効な加速度センサーを搭載したデバイスで重力の力が変化すると、発射されます - モバイルデバイスなど
ユーザーがギロピタスを搭載したデバイスを回転させたときに発射されます。
ゲームパッドがクライアントに接続されたときに発火します。接続されたゲームパッドの「gamepadNum」をパスします。
ゲームパッドがクライアントから切断されると発火します。切断されたゲームパッドの Enum.UserInputType をパスします。
ユーザーが人間-コンピューターインターフェイス装置 (マウスやゲームパッドなど) を介して交流を開始すると発射されます - たとえば、
ユーザーが人間-コンピューターインターフェイスデバイスを介して相互作用する方法を変更したときに発射されます。
ユーザーが人工知能インターフェイス装デバイスを介しての相互作用を停止すると、発火します。
クライアントがキャラクターをジャンプさせるリクエストをするたびに発動します。
クライアントの Enum.UserInputType が変更されたときに発火します。
- PointerAction(wheel : number,pan : Vector2,pinch : number,gameProcessedEvent : boolean):RBXScriptSignal
ユーザーが特定のポイントアクション (ホイール、ピンチ、パン) を実行すると発火します。
クライアントが TextBox に焦点を合わせなくなったときに発射されます。
クライアントが TextBox に焦点を合わせたときに発射されます。
- TouchDrag(dragDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
タッチ可能なデバイスの画面からユーザーが指を解放すると発射される - 例えば、モバイルデバイスの画面。
- TouchLongPress(touchPositions : Array,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
タッチ有効のデバイスの同じ画面位置で、ユーザーが少しの時間、少なくとも 1本の指を保持するときに発射されます - 例えば、モバイルデバイスの画面です。
ユーザーがタブレットやスマートフォンなどのデバイスで指を動かすと、TouchEnabled 発火します。
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
ユーザーが少なくとも 1本の指をTouchEnabledデバイスにドラッグすると発射される - モバイルデバイスの画面など。
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
ユーザーが指を TouchEnabled デバイスに挟むと発射する - モバイルデバイスの画面など。
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState,gameProcessedEvent : boolean):RBXScriptSignal
ユーザーが TouchEnabled デバイスの 2本の指を回転させるときに発火 - モバイルデバイスの画面など。
ユーザーがタッチ可能なデバイスに指を置くと発射される - 例えば、Apple iPad または iPhone の画面、または Google Android 電話。
- TouchSwipe(swipeDirection : Enum.SwipeDirection,numberOfTouches : number,gameProcessedEvent : boolean):RBXScriptSignal
ユーザーが画面に指を下に置き、画面を横切り、特定の移動速度で指を上げると、デバイスの TouchEnabled で炎が発生します。
ユーザーが指をTouchEnabled デバイスにタップすると発射する - モバイルデバイスの画面など。
ユーザーが TouchEnabled デバイスの画面でゲームワールドをタップすると、炎が上がる - モバイルデバイスの画面など。
Roblox クライアントのウィンドウがユーザーの画面に焦点を合わせなくなったときに発火します。
Roblox クライアントのウィンドウがユーザーの画面に焦点を合わせると発火します。
プロパティ
AccelerometerEnabled
このプロパティは、ユーザのデバイスに加速度センサーがあるかどうかを説明します
加速度センサーは、スピード変更(加速)を測定するモバイルデバイスのほとんどに見られるコンポーネントです。
たとえば、次のコードスニペットでは、ユーザーのデバイスに加速度センサーがあるかどうかをチェックする方法を示しています。
local UserInputService = game:GetService("UserInputService")local accelerometerEnabled = UserInputService.AccelerometerEnabledif accelerometerEnabled thenprint("Accelerometer enabled!")elseprint("Accelerometer not enabled!")end
デバイスに加速度センサーが有効である場合、UserInputService:GetDeviceAcceleration() 関数を使用してデバイスの現在の加速度を取得するか、UserInputService.DeviceAccelerationChanged イベントを使用してデバイスの加速度が変更されるときに追跡できます。
As UserInputService はクライアント側のみであるため、このプロパティは LocalScript でのみ使用できます。
コードサンプル
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
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() を使用して、接続されたゲームパッドのリストを取得できます。
As UserInputService はクライアント側のみであるため、このプロパティは LocalScript でのみ使用できます。
参照してください:
コードサンプル
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.GyroscopeEnabledif gyroIsEnabled thenprint("Gyroscope is enabled!")elseprint("Gyroscope is not enabled!")end
As UserInputService はクライアント側のみであるため、このプロパティは LocalScript でのみ使用できます。
コードサンプル
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() をチェックするかどうかをチェックしたい場合に重要なものです。
As UserInputService はクライアント側のみであるため、このプロパティは LocalScript でのみ使用できます。
コードサンプル
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 枚列に基づいてどのように動作するかを設定します。3つの値に設定できます:
- Enum.MouseBehavior.Default — マウスはユーザーの画面上を自由に移動します。
- Enum.MouseBehavior.LockCenter — マウスはロックされており、ユーザーの画面の中心から移動できません。
- Enum.MouseBehavior.LockCurrentPosition — マウスはロックされ、ロック時にユーザーの画面の現在の位置から移動できません。
このプロパティの値は、イベント追跡マウス移動の感度に影響しません。たとえば、 GetMouseDelta は、マウスがロックされているかどうかに関係なく、ピクセルで同じ Vector2 画面位置を返します。ユーザーの画面で自由に移動できるかどうかに関係なく。結果として、カメラを制御するデフォルトのスクリプトは、このプロパティの影響を受けません。
このプロパティは、 に を有効にし、プレイヤーの右マウスボタンが下にない限り、オーバーライドされます。
マウスがロックされている場合、UserInputService.InputChanged はプレイヤーがマウスを動かしたときに引き続き発射し、マウスが移動しようとしたデルタを通過します。さらに、プレイヤーがゲームから追放された場合、マウスは強制的にアンロックされます。
As UserInputService はクライアント側のみであるため、このプロパティは 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
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() の場合には InputObject.Delta を返します。たとえば、 GetMouseDelta は常に (0、0) を返します。
コードサンプル
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 thenprint("The user's device has an available mouse!")elseprint("The user's device does not have an available mouse!")end
UserInputService マウス機能を使用する前に、UserInputService:GetMouseLocation() などのこれをチェックすることが重要です。
As UserInputService はクライアント側のみであるため、このプロパティは 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
MouseIcon プロパティは、ポインターとして使用される画像を決定します。空白の場合、デフォルトの矢印が使用されます。カーソルが ImageButton 、 TextButton 、 TextBox 、または ProximityPrompt などの特定の UI オブジェクトの上に停留する間、この画像は上書きされ、一時的に無視されます。
カーソルを完全に非表示にするには、透明な画像を使用しないでください しない 。代わりに、UserInputService.MouseIconEnabled を偽に設定します。
コードサンプル
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
As UserInputService はクライアント側のみであるため、このプロパティは 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
このプロパティは、画面上のキーボードの位置をピクセルで説明します。キーボードの位置は、表示されていないときは Vector2.new(0, 0) です。
As UserInputService はクライアント側のみであるため、このプロパティは LocalScript または Script でのみ使用でき、RunContext に設定された Enum.RunContext.Client でのみ使用できます。
See also OnScreenKeyboardVisible と OnScreenKeyboardSize 。
コードサンプル
local UserInputService = game:GetService("UserInputService")
print(UserInputService.OnScreenKeyboardPosition)
OnScreenKeyboardSize
このプロパティは、ピクセルで画面上のキーボードのサイズを説明します。キーボードのサイズは、表示されていないときは Vector2.new(0, 0) です。
As UserInputService はクライアント側のみであるため、このプロパティは LocalScript または Script でのみ使用でき、RunContext に設定された Enum.RunContext.Client でのみ使用できます。
See also OnScreenKeyboardVisible と OnScreenKeyboardPosition 。
OnScreenKeyboardVisible
このプロパティは、画面上のキーボードが現在ユーザーの画面に表示されているかどうかを説明します。
As UserInputService はクライアント側のみであるため、このプロパティは LocalScript または Script でのみ使用でき、RunContext に設定された Enum.RunContext.Client でのみ使用できます。
See also OnScreenKeyboardSize と OnScreenKeyboardPosition 。
TouchEnabled
このプロパティは、ユーザーの現在のデバイスにタッチスクリーンが利用可能かどうかを説明します。
プロパティは、ユーザーのデバイスにタッチスクリーンがあるかどうかを判断し、結果としてタッチイベントが発動するかどうかを決定するために使用されます。TouchEnabled が true の場合、UserInputService.TouchStarted や UserInputService.TouchEnded などのユーザーインプットサービスイベントを使用して、ユーザーがデバイスの画面に触れ始めて停止する時間を追跡できます。
以下のコードスニペットは、ユーザーのデバイスにタッチスクリーンがあるかどうかを印刷します。
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
参照してください:
コードサンプル
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.VREnabledif isUsingVR thenprint("User is using a VR headset!")elseprint("User is not using a VR headset!")end
As UserInputService はクライアント側のみであるため、このプロパティは 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
方法
GamepadSupports
この機能は、指定された Enum.UserInputType ゲームパッドが指定された Enum.KeyCode に対応するボタンをサポートしているかどうかを返します。この機能は、有効なゲームパッド入力を決定するために使用されます。
どの Enum.UserInputType ゲームパッドが接続されているかを決定するには、UserInputService:GetConnectedGamepads() を使用します。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
参照してください:
パラメータ
ゲームパッドの Enum.UserInputType 。
問題のボタンの Enum.KeyCode 。
戻り値
指定されたゲームパッドが、指定された Enum.KeyCode に対応するボタンをサポートしているかどうか。
コードサンプル
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
この関数は、現在接続されているゲームパッドのアレイを返します Enum.UserInputTypeゲームパッドが接続されていない場合、この配列は空になります。さらに、ゲームパッドのユーザーインプットタイプオブジェクトだけを返します。たとえば、このイベントは接続された Gamepad1 オブジェクトを返すが、キーボードオブジェクトは返さない。
たとえば、次のコードスニペットは、接続されたゲームパッドを取得し、 接続されたゲームパッド という変数に保存します。
local UserInputService = game:GetService("UserInputService")local connectedGamepads = UserInputService:GetConnectedGamepads()
特定のゲームパッドが接続されているかどうかを確認するには、UserInputService:GetGamepadConnected() を使用します。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
参照してください:
戻り値
ユーザーのデバイスに接続されたゲームパッドと一致する UserInputTypes の配列。
コードサンプル
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 でのみ使用できます。
戻り値
コードサンプル
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 を返します。
重力ベクトルは、装置の重力の実世界の力に対する向きによって決定されます。たとえば、デバイスが完全に縦向き (ポートレート) である場合、重力ベクトルは Vector3.new(0, 0, -9.18) です。装置の左側が下を向いている場合、ベクトルは Vector3.new(9.81, 0, 0) です。最後に、デバイスの後ろが下を向いている場合、ベクトルは Vector3.new(0, -9.81, 0) です。
この機能は、ユーザーのデバイスをゲーム内で重力に影響を与えたり、ボールなどのゲームオブジェクトを移動させるために使用できます。
重力は、モバイルデバイスなどのギロピタスを有効にした装置を使用しているプレイヤーのみが追跡されます - たとえば、グローバルナビゲーション
ユーザーのデバイスにジロスコープが有効かどうかをチェックするには、UserInputService.GyroscopeEnabled の値をチェックします。デバイスに加速度センサーが有効である場合、UserInputService.DeviceGravityChanged イベントを使用して、ユーザーデバイスの重力フォースが変更されたときを追跡できます。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
戻り値
コードサンプル
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
この機能は、デバイスの現在の回転ベクトルを説明する InputObject と CFrame を返します。
これは InputObject で発射されます。入力オブジェクトの 位置 プロパティは、各ローカルデバイス軸の合計回転を追跡する Enum.InputType.Gyroscope です。
デバイスの回転は、gyroscope を持つデバイスでのみ追跡できます。
この機能はローカルで発動するため、LocalScript でのみ使用できます。
戻り値
2つのプロパティを含むtuple:
- デルタプロパティは、最後に起こった回転量を説明します
- CFレームは、デバイスの現在の回転がデフォルトの参照フレームに対しての回転です。
コードサンプル
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 を返します。A TextBox はユーザーによって手動で選択できます、または TextBox:CaptureFocus() 関数を使用して選択を強制できます。TextBox が選択されない場合、この関数は nil を返します。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
参照してください: See Also
戻り値
GetGamepadConnected
この機能は、指定された Enum.UserInputType を持つゲームパッドがクライアントに接続されているかどうかを返します。
これを使用して、特定のゲームパッド、例えば 'Gamepad1' がクライアントのデバイスに接続されているかどうかをチェックできます。
すべての接続されたゲームパッドのリストを取得するには、UserInputService:GetConnectedGamepads() を使用します。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
参照してください:
パラメータ
問題のゲームパッドの Enum.UserInputType 。
戻り値
ゲームパッドが Enum.UserInputType に接続されているかどうか。
コードサンプル
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 でのみ使用できます。
参照してください:
パラメータ
問題のゲームパッドに対応する Enum.UserInputType
戻り値
InputObjects 現在のゲームパッドのすべての入力の状態を表す配列。
GetImageForKeyCode
このメソッドは、リクエストされた Enum.KeyCode を受け取り、現在接続されているゲームパッドデバイス (Xbox、PlayStation および Windows のみ) に対応する画像を返します。つまり、接続されたコントローラーが Xbox ワン コントローラーである場合、ユーザーは Xbox アセットを見ることができます。同様に、接続されたデバイスがプレイステーションコントローラーである場合、ユーザーはプレイステーションアセットを見ます。カスタムアセットを使用したい場合は、GetStringForKeyCode() を参照してください。
パラメータ
関連する画像を取得するための Enum.KeyCode 。
戻り値
返された画像アセット ID。
コードサンプル
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() を使用します。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
戻り値
現在押されているキーと関連する InputObjects の配列。
コードサンプル
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
この機能は、ユーザーの最新の入力に関連付けられた 'Enum.UserInputType' を返します。
たとえば、ユーザーの前の入力がスペースバーを押していた場合、返された Enum.UserInputType は 'キーボード' になります。
UserInputService.LastInputTypeChanged イベントは、ユーザーが最後に使用した Enum.UserInputType がいつ変更されたかを追跡するのに使用できます。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
戻り値
ユーザーの最新の入力に関連する Enum.UserInputType 。
コードサンプル
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 のアレイを返します。
この機能によって追跡されるマウスボタンには、次のものがあります:
<td>説明</td></tr></thead><tr><td>マウスボタン1</td><td>左マウスボタン。</td></tr><tr><td>マウスボタン2</td><td>右マウスボタン。</td></tr><tr><td>マウスボタン3</td><td>中央のマウスボタン。</td></tr>
名前 |
---|
ユーザーが機能を呼び出したときにマウスのボタンを押さない場合、空の配列が返されます。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
戻り値
現在押されているマウスボタンに対応する InputObjects の配列。
コードサンプル
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.MouseBehavior プロパティを使用してロックされている場合にのみ機能します。マウスがロックされていない場合、返された Vector2 値はゼロになります。
クライアントの設定と UserInputService.MouseDeltaSensitivity で決定されたマウスの感度は、結果に影響を与えます。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
戻り値
マウスの移動変更。
コードサンプル
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)
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
この機能は、ピクセルで上左隅に対するプレイヤーの Mouse の現在の画面位置を表す Vector2 を返します。これは、Enum.ScreenInsets を考慮しない; 上左と下右の挿入を取得するには、GuiService:GetGuiInset() を呼び出す。
マウスポインタの位置が画面外であるか、プレイヤーのデバイスにマウスがない場合、返された値は未定義になります。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
戻り値
コードサンプル
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 を制御するゲームパッドを決定するだけです。ナビゲーションコントロールに影響を与えません。
Since UserInputService はクライアント側のみなので、この関数は LocalScript でしか使用できません。
参照してください:
- UserInputService:SetNavigationGamepad() , GUI ナビゲーション用のゲームパッドを有効化または無効化する
- UserInputService:IsNavigationGamepad() , GUI ナビゲーション用にゲームパッドが有効になっているかどうかを確認する
- UserInputService:GetConnectedGamepads() , GUIナビゲーション制御に関係なく接続されたすべてのゲームパッドを返す
戻り値
優先度順に GUI ナビゲーションに使用できる UserInputTypes の配列。
GetStringForKeyCode
GetStringForKeyCode は、ユーザーが指定の Enum.KeyCode を入力するために押す必要のあるキーを表す文字列を返し、キーボードレイアウトを考慮します。キーコードが変更者を保持する必要がある場合、この関数は変更者に加えて押されるキーを返します。以下の例を参照して、さらに説明します。
非 QWERTY キーボードレイアウトで Roblox を使用すると、キーコードが同等の QWERTY 位置にマップされます。たとえば、AZERTY キーボードで A を押すと、Enum.KeyCode.Q が結果になります。このマッピングは、エクスペリエンス UI 要素の一致しない情報につながる可能性があります。たとえば、「マップを開くには、M を押す」は AZERTY キーボードでは不正確で、「マップを開くには、? を押す」が QWERTY の同じ位置にある M と同じ位置にある必要がある。この機能は、非 QWERTY キーボードレイアウトを使用している間に押される実際のキーを提供して、この問題を解決します。
local UserInputService = game:GetService("UserInputService")local textLabel = script.Parentlocal mapKey = Enum.KeyCode.MtextLabel.Text = "Press " .. UserInputService:GetStringForKeyCode(mapKey) .. " to open the map"
QWERTY キーボードの例
<th>返却値</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.Exists の</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.At</code></td><td><code>2</code> なぜなら <code>@</code> は <kbd>Shift</kbd><kbd>2</kbd> でタイプされているからです</td></tr></tbody>
キーコード |
---|
AZERTY キーボードの例
<th>返却値</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.Exists の</code></td><td><code>=</code></td></tr><tr><td><code>Enum.KeyCode.At</code></td><td><code>É</code></td></tr></tbody>
キーコード |
---|
ゲームパッドの使用
最も最近に接続されたゲームパッドのストリングマッピングを返します。接続されたコントローラーがサポートされていない場合、機能はリクエストされたキーコードのデフォルトの文字列変換を返します。
次の例では、カスタムアセットをマップする方法を示しています 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
ゲームパッドマッピング
方向パッドキーコードは、デバイスに基づいて差異がありません。Enum.KeyCode.ButtonSelect は、いくつかの場合、少し異なる動作を示します。両方のプレイステーションマッピングを使用して、ユーザーが正しいボタンを見るようにします。
<th>PlayStation の返却値</th><th>Xbox の返却値</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonA</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>Enum.KeyCode.ButtonY</code></td><td><code>ボタン三角形</code></td><td><code>ボタンY</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><code>ボタンL1</code></td><td><code>ボタンLB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL2</code></td><td><code>ボタンL2</code></td><td><code>ボタンLT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL3</code></td><td><code>ボタンL3</code></td><td><code>ボタンLS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><code>ボタンR1</code></td><td><code>ボタンRB</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR2</code></td><td><code>ボタンR2</code></td><td><code>ボタンRT</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><code>ボタンR3</code></td><td><code>ボタンRS</code></td></tr><tr><td><code>Enum.KeyCode.ButtonStart</code></td><td><code>ボタンオプション</code></td><td><code>ボタン開始</code></td></tr><tr><td><code>Enum.KeyCode.ButtonSelect</code></td><td><code>ボタンタッチパッド</code> と <code>ボタンシェア</code></td><td><code>ボタン選択</code></td></tr></tbody>
キーコード |
---|
キーコードのシステムイメージ
ユーザーインターフェイス内の Enum.KeyCode など、画像としてよりよく表現できる ImageLabel を使用するとき、次のレガシーアイコンを使用できます。ただし、Xbox と PlayStation コントローラーアイコンを回収するためのより現代的でクロスプラットフォームの方法として GetImageForKeyCode() を使用することをお勧めします。
<th>画像</th><th>アセット ID</th></tr></thead><tbody><tr><td><code>Enum.KeyCode.ButtonX</code></td><td><img src="../../../assets/scripting/controls/xboxX.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxX.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonY</code></td><td><img src="../../../assets/scripting/controls/xboxY.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxY.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonA</code></td><td><img src="../../../assets/scripting/controls/xboxA.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxA.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonB</code></td><td><img src="../../../assets/scripting/controls/xboxB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxB.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadLeft</code></td><td><img src="../../../assets/scripting/controls/dpadLeft.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadLeft.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadRight</code></td><td><img src="../../../assets/scripting/controls/dpadRight.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadRight.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadUp</code></td><td><img src="../../../assets/scripting/controls/dpadUp.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadUp.png</code></td></tr><tr><td><code>Enum.KeyCode.DPadDown</code></td><td><img src="../../../assets/scripting/controls/dpadDown.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/dpadDown.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonSelect</code></td><td><img src="../../../assets/scripting/controls/xboxView.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxView.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonStart</code></td><td><img src="../../../assets/scripting/controls/xboxmenu.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxmenu.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL1</code></td><td><img src="../../../assets/scripting/controls/xboxLB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLB.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR1</code></td><td><img src="../../../assets/scripting/controls/xboxRB.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRB.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL2</code></td><td><img src="../../../assets/scripting/controls/xboxLT.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLT.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR2</code></td><td><img src="../../../assets/scripting/controls/xboxRT.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRT.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonL3</code></td><td><img src="../../../assets/scripting/controls/xboxLS.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLS.png</code></td></tr><tr><td><code>Enum.KeyCode.ButtonR3</code></td><td><img src="../../../assets/scripting/controls/xboxRS.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRS.png</code></td></tr><tr><td><code>Enum.KeyCode.Thumbstick1</code></td><td><img src="../../../assets/scripting/controls/xboxLSDirectional.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxLSDirectional.png</code></td></tr><tr><td><code>Enum.KeyCode.Thumbstick2</code></td><td><img src="../../../assets/scripting/controls/xboxRSDirectional.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/xboxRSDirectional.png</code></td></tr><tr><td><code>Enum.KeyCode.バックスペース</code></td><td><img src="../../../assets/scripting/controls/backspace.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/回転スペース.png</code></td></tr><tr><td><code>Enum.KeyCode.Return</code></td><td><img src="../../../assets/scripting/controls/return.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/return.png</code></td></tr><tr><td><code>Enum.KeyCode.左シフト</code></td><td><img src="../../../assets/scripting/controls/shift.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/ shifted.png</code></td></tr><tr><td><code>Enum.KeyCode.RightShift</code></td><td><img src="../../../assets/scripting/controls/shift.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/ shifted.png</code></td></tr><tr><td><code>Enum.KeyCode.Tab</code></td><td><img src="../../../assets/scripting/controls/tab.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/tab.png</code></td></tr><tr><td><code>Enum.KeyCode.アポストロフ</code></td><td><img src="../../../assets/scripting/controls/apostrophe.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/apostrophe.png</code></td></tr><tr><td><code>Enum.KeyCode.Comma</code></td><td><img src="../../../assets/scripting/controls/comma.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/comma.png</code></td></tr><tr><td><code>Enum.KeyCode.バッククォート</code></td><td><img src="../../../assets/scripting/controls/graveaccent.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/graveaccent.png</code></td></tr><tr><td><code>Enum.KeyCode.Period</code></td><td><img src="../../../assets/scripting/controls/period.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/期間.png</code></td></tr><tr><td><code>Enum.KeyCode.Space</code></td><td><img src="../../../assets/scripting/controls/spacebar.png" width="24"></img></td><td><code>rbxasset://textures/ui/Controls/空白バー.png</code></td></tr></tbody>
キーコード |
---|
パラメータ
戻り値
GetSupportedGamepadKeyCodes
この関数は、指定された Enum.UserInputType に関連付けられたゲームパッドがサポートする KeyCodes のアレイを返します。
この機能を使用すると、接続されたゲームパッドによってサポートされないキーコードを判断できます。特定のキーコードがサポートされているかどうかを判断するには、UserInputService:GamepadSupports() を使用します。
存在しない、または接続されていないゲームパッドに呼び出された場合、この関数は空の配列を返します。
As UserInputService はクライアント側のみであるため、この機能は LocalScript でのみ使用できます。
参照してください:
パラメータ
ゲームパッドの Enum.UserInputType 。
戻り値
コードサンプル
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
この機能は、特定のゲームパッドで特定のボタンが押されているかどうかをチェックします。それは、true に gamepad が指定された button を押し下げている場合、そうでない場合は false を返す。
有効なユーザー入力タイプ
指定されたゲームパッドは、次のユーザーインプットタイプ枚列値の 1つである必要があります:
<tr><td>Enum.UserInputType.ゲームパッド1-8</td></tr>
名前 |
---|
有効なキーコード
指定されたボタンは、次のキーコード枚列値の 1つである必要があります:
<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>
名前 |
---|
これを使用して、A などの特定のボタンが押されているかどうかをチェックできます。例:
local UserInputService = game:GetService("UserInputService")local button = Enum.KeyCode.ButtonAlocal gamepad = Enum.UserInputType.Gamepad1local isButtonHeld = UserInputService:IsGamepadButtonDown(gamepad, button)
Since UserInputService はクライアント側のみなので、この関数は LocalScript でしか使用できません。
参照してください:
パラメータ
指定されたゲームパッドの Enum.UserInputType 。
指定されたボタンの Enum.KeyCode 。
戻り値
指定されたゲームパッドのボタンが押されているかどうかが押されます。
コードサンプル
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
この関数は、ユーザーが指定された Enum.KeyCode に関連するキーを長押ししているかどうかを返します。指定されたキーが押された場合は true 、押されなかった場合は false を返します。
これを使用して、スペースバーなどの特定のキーが押されているかどうかをチェックできます。例:
local UserInputService = game:GetService("UserInputService")local spaceHeld = UserInputService:IsKeyDown(Enum.KeyCode.Space)
ユーザーが押したすべてのキーのリストを取得するには、UserInputService:GetKeysPressed() 関数を使用します。
Since UserInputService はクライアント側のみなので、この関数は LocalScript でしか使用できません。
参照してください:
- Enum.UserInputType.IsGamepadButtonDown - 異なる使用法を持つ同様のイベント: 特定の button が gamepad 上で押されているかどうかをチェックする。
パラメータ
キーの Enum.KeyCode 。
戻り値
指定されたキーが押されているかどうか。
コードサンプル
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
この関数は、マウスのボタンを取り Enum.UserInputType 、現在押されているかどうかを示す bool を返します。
チェックされたマウスボタンは、Enum.UserInputType 引数としてパスされた機能によって決まります。たとえば:
local UserInputService = game:GetService("UserInputService")local pressed = UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)
Since UserInputService はクライアント側のみなので、この関数は LocalScript でしか使用できません。
パラメータ
マウスボタンの Enum.UserInputType 。
戻り値
指定されたマウスボタンが現在押され続けているかどうか。
コードサンプル
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
この機能は、指定された ゲームパッドがナビゲーションと選択を制御することを許可されている場合、 を返します。
ナビゲーションゲームパッドを設定したい場合は、UserInputService:SetNavigationGamepad() を使用できます。すべてのナビゲーションゲームパッドのリストを取得するには、UserInputService:GetNavigationGamepads() を使用できます。
たとえば、以下のコードは、ゲームパッド1がナビゲーションゲームパッドとして存在するかどうかをチェックします:
local UserInputService = game:GetService("UserInputService")if UserInputService:IsNavigationGamepad(UserInputType.Gamepad1) thenprint("Gamepad is a navigation gamepad!")elseprint("Gamepad is not a navigation gamepad!")end
ナビゲーションに関係なく、接続されたすべてのゲームパッドのリストを取得できます`UserInput/GetConnectedGamepads。
Since UserInputService はクライアント側のみなので、この関数は LocalScript でしか使用できません。
参照してください:
パラメータ
指定されたゲームパッドの Enum.UserInputType 。
戻り値
指定されたゲームパッドがナビゲーションゲームパッドかどうか。
RecenterUserHeadCFrame
この機能は、VR ヘッドセットの CFrame をユーザーが着用しているヘッドセットの現在の方向に戻します。これは、ヘッドセットの現在の方向が CFrame.new() に設定されていることを意味します。
この機能を使用して、ヘッドセットの CFrame を奇妙なオフセットになっているように見える場合、プレイエリアの中心に移動します。
これは、VRService 機能と同じように動作します。VRService:RecenterUserHeadCFrame() .
Since UserInputService はクライアント側のみなので、この関数は LocalScript でしか使用できません。
戻り値
コードサンプル
local UserInputService = game:GetService("UserInputService")
UserInputService:RecenterUserHeadCFrame()
SetNavigationGamepad
SetNavigationGamepad 機能は、指定された Enum.UserInputType ゲームパッドが GUI ナビゲーターを移動できるかどうかを設定します。GUI ナビゲーターを移動できるゲームパッドは、ナビゲーションゲームパッド と考えられます。
有効 引数が true としてパスされると、ゲームパッドは GUI ナビゲータを移動できます。引数が false である場合、ゲームパッドは GUI ナビゲータを移動できません。
特定のゲームパッドがナビゲーションゲームパッドとして設定されているかどうかをチェックしたい場合は、UserInputService:IsNavigationGamepad() 関数を使用できます。また、UserInputService:GetNavigationGamepads() を使用して、すべてのナビゲーションゲームパッドのリストを取得できます。
Since UserInputService はクライアント側のみなので、この関数は LocalScript でしか使用できません。
参照してください:
パラメータ
指定されたゲームパッドの Enum.UserInputType 。
指定されたゲームパッドが GUI ナビゲーターを移動できるかどうか。
戻り値
コードサンプル
local UserInputService = game:GetService("UserInputService")
UserInputService:SetNavigationGamepad(Enum.UserInputType.Gamepad1, true)
イベント
DeviceAccelerationChanged
デバイス加速変更イベントは、ユーザーが加速度センサーを持つデバイスを移動すると発動します。
加速度センサーは、スピード変更(加速)を測定するモバイルデバイスのほとんどに見られるコンポーネントです。
ユーザーのデバイスに加速度センサーが有効かどうかを判断するには、UserInputService.AccelerometerEnabled を参照してください。
このイベントは、加速度センサーを持つデバイスの動作を追跡するために使用できます。サンプル使用には、モバイルデバイスが加速するとプレイヤーキャラクターを移動することが含まれます。
さらに、このイベントは UserInputService:GetDeviceAcceleration() と一緒に使用して、デバイスに加速度センサーがある場合、ユーザーのデバイスの現在の動作を決定することができます。
このイベントはローカルでのみ発動します - つまり、デバイスが移動するプレイヤーのみがイベントを使用でき、それは LocalScript でのみ機能します。
パラメータ
InputObject 、UserInputType の ** 、そして各ローカルデバイス軸の重力の力を示す Position 。
コードサンプル
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
デバイスの重力 UserInputService.DeviceGravityChanged がアクセラレータを持つデバイスで変更されると、イベント Vector3 が発動します。
デバイスの重力ベクトルは、デバイスの X、Y、および Z軸のそれぞれに対する重力の力を表します。重力は決して変わらないが、デバイスが回転して方向を変更すると、それぞれの軸に対する力が変化する。各軸に適用される力値は、-1から 1までのユニットベクトルです。
加速度センサーは、スピード変更(加速)を測定するモバイルデバイスのほとんどに見られるコンポーネントです。
このイベントは、ユーザーのデバイス上の重力の実世界方向を決定するために使用できます。これは、ゲーム内のオブジェクト (下の例を参照) など、ゲーム内のユーザーデバイス上の重力の力をシミュレートするのにも使用できます。
ユーザーのデバイスに加速度センサーが有効かどうかを確認するには、UserInputService.AccelerometerEnabled を参照してください。デバイスに加速度センサーが有効になっている場合、UserInputService:GetDeviceGravity() 関数を使用して、ユーザーデバイスの現在の重力の力を取得できます。
パラメータ
InputObject 、各ローカルデバイス軸の重力の強度を示す InputObject.Position プロパティを持つこの位置は、装置に対する重力方向を決定するための方向として使用できます。
コードサンプル
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
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
装置回転変更イベントは、ユーザーがジロスコープを持つデバイスを回転させたときに発動します。
ジロスコープは、方向と回転速度を検出するモバイルデバイスのほとんどに見られるコンポーネントです。
イベントは、デバイスの向きとユーザーがデバイスを回転させるときの変更を追跡するときに便利です。現在のデバイス回転を決定するには、UserInputService:GetDeviceRotation() 関数を使用できます。
ユーザーのデバイスにジロスコープが有効であるかどうかをチェックし、このイベントが発動するかどうかを確認するには、UserInputService.GyroscopeEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
パラメータ
デバイスの回転に関する情報を提供する Class.InputObject``Class.InputObject.Position は新しい回転を Vector3 位置値として表し、InputObject.Delta は位置値 Vector3 での回転変更を表します。
コードサンプル
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
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
ゲームパッド接続イベントは、ゲームパッドがクライアントに接続されたときに発動します。
Roblox ゲームは複数のコントローラーをサポートしているため、このイベントは、UserInputService.GamepadDisconnected イベントとペアになって、アクティブなコントローラー/ゲームパッドを追跡するときに便利です。UserInputService:GetConnectedGamepads() を使用して、使用する正しいゲームパッドを見つけることもできます。
次の例では、ゲームパッドがクライアントに接続されたときの追跡の使用例を示しています。
local UserInputService = game:GetService("UserInputService")
local function GamepadConnected(gamepad)
print("Player has plugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadConnected:Connect(GamepadConnected)
どのデバイスが接続されているかを見たい場合は、UserInputService:GetConnectedGamepads() 関数を使用できます。
このイベントはローカルで発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
接続されたゲームパッドの Enum.UserInputType 。
GamepadDisconnected
ゲームパッド切断イベントは、ゲームパッドが切断されたときに発動します。
Roblox ゲームは複数のコントローラーをサポートしているため、このイベントは、UserInputService.GamepadConnected イベントとペアになって、アクティブなコントローラー/ゲームパッドを追跡するときに便利です。UserInputService:GetConnectedGamepads() を使用して、使用する正しいゲームパッドを見つけることもできます。
次の例では、ゲームパッドがクライアントから切断されたときの追跡の使用例を示しています。
local UserInputService = game:GetService("UserInputService")
local function GamepadDisconnected(gamepad)
print("Player has unplugged controller: " .. tostring(gamepad))
end)
UserInputService.GamepadDisconnected:Connect(GamepadDisconnected)
このイベントはローカルで発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
切断されたゲームパッドの Enum.UserInputType
InputBegan
InputBegan イベントは、ユーザーが人間-コンピューターインターフェイス装置 (マウスボタンを下、タッチ開始、キーボードボタンを下など) を介して交流を開始すると発動します。
ユーザーが GUI 要素、ゲームパッドなどと最初に対話するときのユーザーインタラクションの開始を追跡するなど、使用できます。マウスホイールの動作はキャプチャしません。
このイベントは、UserInputService.InputChanged と UserInputService.InputEnded と一緒に使用して、ユーザーの入力が開始、変更、終了するタイミングを追跡できます。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
パラメータ
ユーザーの入力に関する情報を含む InputObject インスタンス。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
-- 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
入力が変更されたイベントは、ユーザーが人間-コンピューターインターフェイスデバイス (マウスボタンを下、タッチ開始、キーボードボタンを下など) を介して対話する方法を変更したときに発動します。
Roblox によって自動的に処理されるイベントを無視するには、ScrollingFrame でスクロールするように、gameProcessedEvent 引数が false であることを確認してください。このイベントは、UserInputService.InputBegan と UserInputService.InputEnded と一緒に使用して、ユーザーの入力が開始、変更、終了するタイミングを追跡できます。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
パラメータ
ユーザーの入力に関する情報を含む InputObject インスタンス。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
-- 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
インプット終了イベントは、ユーザーが人間-コンピューターインターフェイスデバイス (マウスボタンを下、タッチ開始、キーボードボタンを下など) を介して交流を停止すると発動します。ユーザーがキーボードキー、マウスボタン、タッチスクリーン入力などをリリースしたときを追跡するときに便利です。
このイベントは、UserInputService.InputBegan と UserInputService.InputChanged と一緒に使用して、ユーザーの入力が開始、変更、終了するタイミングを追跡できます。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
パラメータ
ユーザーの入力に関する情報を含む InputObject インスタンス。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
-- 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
クライアントからジャンプリクエストが発生したとき、例えば、クライアントがスペースバーまたはモバイルでジャンプボタンを押すとき、UserInputService ジャンプリクエストイベントが発動します。
このイベントは、ユーザーがPlayer.Characterを試みるたびに発動します。デフォルト動作は、プレイヤーの Humanoid.Jump プロパティを真に設定してジャンプリクエストに応答し、プレイヤーのキャラクターがジャンプするようにします。
イベントは、プレイヤーがジャンプしたいと思ったときを追跡するのに使用できます。プレイヤーをジャンプさせるために使用するのではなく、デフォルトのジャンプ動作を変更するために使用する必要があります - 例えば、ジャンプを無効にするなどです。
たとえば、以下のコードは、プレイヤーがジャンプリクエストを送るたびに「ジャンプ」を出力します。
local UserInputService = game:GetService("UserInputService")
function onJumpRequest()
print("Jump!")
end
UserInputService.JumpRequest:Connect(onJumpRequest)
このイベントは、1回のジャンプリクエストで複数回発動するため、デバウンス を使用することを推奨します。
キーやボタンを他のアクションに接続したい場合は、UserInputService:GetKeysPressed() や UserInputService.InputBegan または ContextActionService などのイベントを使用することを検討してください。
このイベントはローカルでのみ発動するため、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
クライアントがヒューマン-コンピューターインターフェイスデバイスを介して相互作用する方法を変更するたびに、UserInputService.LastInputTypeChangedイベントが発動します。(i.e.マウス移動からマウスホイールへ、または Thumbstick1 から Thumbstick2 へ)。
最後の入力タイプの値を取得するには、変更されたかどうかに関係なく、UserInputService:GetLastInputType() 関数を使用できます。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
パラメータ
最後の入力タイプを示す A Enum.UserInputType
コードサンプル
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
ポインタアクション は、ユーザーが特定のポインタアクション操作実行したときに発動します。特に、マウスホイールをスクロールすること。
パラメータ
TextBoxFocusReleased
クライアントが TextBoxFocusReleased の焦点を失うと、クライアントが TextBox に停止してテキスト入力を停止するとき、または画面の他の場所を押すかクリック/タッチすると、通常、クライアントがイベントを発動します。
たとえば、以下のコードは、イベントが発動したときに焦点を失う TextBox の名前を印刷します。
local UserInputService = game:GetService("UserInputService")
function TextBoxFocusReleased(textbox)
print(textbox.Name)
end
UserInputService.TextBoxFocusReleased:Connect(TextBoxFocusReleased)
UserInputService.TextBoxFocused と一緒に使用して、TextBox が焦点を獲得して失うタイミングを追跡できます。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください: See Also
パラメータ
TextBoxFocused
このイベントは、クライアントがテキストボックスをクリック/タップしてテキスト入力を開始するときなど、TextBox にフォーカスが当たると発動します。これは、TextBox:CaptureFocus() を使用してテキストボックスの焦点が焦点化された場合も発動します。
たとえば、以下のコードは、イベントが発動したときに焦点が当たった TextBox の名前を印刷します。
local UserInputService = game:GetService("UserInputService")
function TextBoxFocused(textbox)
print(textbox.Name)
end)
UserInputService.TextBoxFocused:Connect(TextBoxFocused)
テキストボックスが焦点を獲得したり失った時を追跡するために、UserInputService.FocusReleased と一緒に使用できます。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください: See Also
パラメータ
TouchEnded
タッチ終了イベントは、ユーザーがタッチ可能なデバイスの画面から指を解放したときに発動し、デバイスでタッチ入力を終了します。
このイベントは、ユーザーがデバイスの画面に触れるのをやめたときを判断するのに使用できます。ユーザーが画面にタッチを開始し、停止するタイミングを決定するために UserInputService.TouchStarted とペアにできます。
たとえば、以下のコードは、ユーザーが画面にタッチをやめた位置を印刷します。
local UserInputService = game:GetService("UserInputService")
function TouchEnded(touch, gameProcessedEvent)
print("Touch ended at " .. tostring(touch.Position))
end
UserInputService.TouchEnded:Connect(TouchEnded)
タッチ入力オブジェクトは、タッチの期間中、同じ入力オブジェクトです。つまり、タッチオブジェクトのときに InputObjects を比較することは、同じ指かどうかを判断するのに有効です。
ユーザーのデバイスが TouchEnabled であるかどうか、およびタッチイベントが発動するかどうかをチェックするには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
ユーザーの入力に関する情報を含む InputObject インスタンス。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
ユーザーがタッチ可能なデバイスの同じ画面位置で、短時間に少なくとも 1 本の指を保持すると、発射されます。
このイベントは、ユーザーがゲーム内の GuiObject または要素に指を押し続ける時間を判断するのに使用できます。
以下の例では、ユーザーが同じ画面位置で少しの時間、少なくとも 1本の指を押し続けると、長押しの state が印刷されます。可能な状態には、開始、変更、終了、キャンセル、およびなしがあります。
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)
ユーザーのデバイスがタッチ有効であるかどうかを確認し、タッチイベントが発動するかどうかを見るには、UserInputService.TouchEnabled を参照してください。
It can be paired with UserInputService.TouchStarted と UserInputService.TouchEnded をペアにして、ユーザーが画面に触れ始めて停止する時を決定できます。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
ジェスチャーの Enum.UserInputState 。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
ユーザーがタブレットやスマートフォンなどのデバイスで指を動かすと、TouchEnabled 発火します。
このイベントは、ユーザーが画面上で指を動かしているかどうか、およびユーザーが指を動かしている場所を追跡するのに便利です。
以下のコードは、タッチが前の位置から TouchEnabled デバイスの新しい位置に移動する様子を示しています。パスされた InputObject.Position パラメータの touch にある Vector3 は、XとYの座標を含むが、Zは常に 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)
このイベントを UserInputService.TouchStarted と UserInputService.TouchEnded でペアにして、ユーザーが画面に触れ始める時、指を動かしている間、画面に触れるのをやめる時を決定します。
ユーザーのデバイスがタッチをサポートし、そのタッチイベントが発動するかどうかを確認するには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
ユーザーの入力に関する情報を含む InputObject インスタンス。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
タッチパンイベントは、ユーザーが少なくとも 1本の指をTouchEnabledデバイスにドラッグすると発動します。
このイベントは、ユーザーがタッチ可能なデバイスの画面で指を動かしたときを判断するのに使用できます - たとえば、カスタムカメラスクリプトで Camera を回転させること。
以下のスニペットは、「タッチドラッグの速度」を印刷し、ユーザーが指を画面にドラッグするときのユーザーのタッチ速度を続けます。
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPan:Connect(function(touchPositions, totalTranslation, velocity, state, gameProcessedEvent)
print("Speed of touch drag: " .. tostring(velocity))
end)
別の便利な UserInputService 機能をここで見てください UserInputService.TouchRotate .
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
開始から終了までのパンジェスチャーのサイズ (ピクセル)。
パンジェスチャーの速度 (ピクセル) 秒ごと。
ジェスチャーの Enum.UserInputState 。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
ユーザーが TouchEnabled デバイスの画面に 2本の指を配置し移動させたときに発射されます。
たとえば、以下のスニペットは、タッチピンチの開始時からカメラズームスケールがどの程度変わったかを印刷します。
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchPinch:Connect(function(touchPositions, scale, velocity, state, gameProcessedEvent)
print("Scale difference since beginning of pinch: " .. tostring(scale))
end)
ユーザーのデバイスが TouchEnabled であるかどうか、およびタッチイベントが発動するかどうかをチェックするには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
開始から終了までのピンチの大きさ (ピクセル) をスタートピンチの位置によって分割した値。
ピンチジェスチャーの速度 (ピクセル毎秒)。
ジェスチャーの Enum.UserInputState 。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
タッチ回転イベントは、ユーザーが TouchEnabled デバイスで 2本の指を回転させると発動します。
たとえば、次のコードは、タッチ回転開始時からカメラがどれほど回転したかを印刷します。
local UserInputService = game:GetService("UserInputService")
UserInputService.TouchRotate:Connect(function(touchPositions, rotation, velocity, state, gameProcessedEvent)
print("Camera has rotated " .. tostring(rotation) .. " degrees!")
end)
ユーザーのデバイスが TouchEnabled であるかどうか、およびタッチイベントが発動するかどうかをチェックするには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
モバイルデバイス上のユーザーのカメラを制御するコアスクリプトは、このイベントと同様の機能を果たすコードを使用します。このイベントのベストプラクティスは、デフォルトのコアスクリプトをオーバーライドするためにモバイルカメラシステムを作成するときに使用することです。
参照してください:
パラメータ
ジェスチャーが開始以来回転した度の数。
回転の変更 (度) を変更時間 (秒) で割った値
ジェスチャーの Enum.UserInputState 。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
タッチ開始イベントは、ユーザーがデバイスの TouchEnabled に指を置いたときに発動し、デバイスでタッチ入力を開始します。
このイベントは、ユーザーがデバイスの画面に触れ始めるタイミングを判断するのに使用できます。ユーザーが画面にタッチを開始し、停止するタイミングを決定するために UserInputService.TouchEnded とペアにできます。
タッチ入力オブジェクトは、タッチの期間中、同じ入力オブジェクトです。つまり、タッチオブジェクトのときに InputObjects を比較することは、同じ指かどうかを判断するのに有効です。
ユーザーのデバイスが TouchEnabled であるかどうか、およびタッチイベントが発動するかどうかをチェックするには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
ユーザーの入力に関する情報を含む InputObject インスタンス。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
ユーザーがデバイスの に指をスワイプすると、イベントが発動します。
このイベントは、ユーザーがデバイスの画面で指をスワイプするタイミングと、スワイプした方向を判断するのに使用できます。
タッチ入力の動作をより精密に追跡するには、UserInputService.TouchMoved を使用してください
ユーザーのデバイスが TouchEnabled であるかどうか、およびタッチイベントが発動するかどうかをチェックするには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
Enum.SwipeDirection 、ユーザーがスワイプした方向を示す。
ジェスチャーに関与するタッチの数 (例: 指)。
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
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
タッチタップイベントは、ユーザーが TouchEnabled デバイスの画面に指をタッチ/タップすると発動します。
このイベントは、ユーザーがゲームワールドまたは GuiObject 要素をタッチ/タップしたかどうかに関係なく発動します。ユーザーがゲームワールドに触れたりタップしたりするときにのみ発動するイベントを検索している場合は、UserInputService.TouchTapInWorld を使用します。
ユーザーのデバイスが TouchEnabled であるかどうか、およびタッチイベントが発動するかどうかをチェックするには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
このイベントはローカルでのみ発動するため、LocalScript でのみ使用できます。
パラメータ
ゲームエンジンが内部でこの入力を観察し、それに対して行動したかどうかを示します。一般的にこれは UI 処理に関連しているので、この入力からボタンがタッチされたかクリックされた場合、gameProcessedEvent が true になります。これは、ContextActionService を介して接続された入力イベントにも当てはまります。
コードサンプル
local UserInputService = game:GetService("UserInputService")
-- The parent of this script (a ScreenGui)
local touchScreenGui = script.Parent
-- Create the GUI frame that the user interacts with through Touch
-- events
local touchGui = Instance.new("Frame")
touchGui.Name = "TouchGui"
touchGui.AnchorPoint = Vector2.new(0.5, 0.5)
-- Fires when the touches their device's screen
local function TouchTap(touchPositions, _gameProcessedEvent)
touchGui.Parent = touchScreenGui
touchGui.Position = UDim2.new(0, touchPositions[1].X, 0, touchPositions[1].Y)
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Fires when a user starts touching their device's screen and does not
-- move their finger for a short period of time
local function TouchLong(_touchPositions, _state, _gameProcessedEvent)
touchGui.Size = UDim2.new(0, 100, 0, 100)
end
-- Fires when the user moves their finger while touching their device's
-- screen
local function TouchMove(touch, _gameProcessedEvent)
touchGui.Position = UDim2.new(0, touch.Position.X, 0, touch.Position.Y)
end
-- Fires when the user stops touching their device's screen
local function TouchEnd(_touch, _gameProcessedEvent)
touchGui.Parent = nil
touchGui.Size = UDim2.new(0, 50, 0, 50)
end
-- Only use the Touch events if the user is on a mobile device
if UserInputService.TouchEnabled then
UserInputService.TouchTap:Connect(TouchTap)
UserInputService.TouchLongPress:Connect(TouchLong)
UserInputService.TouchMoved:Connect(TouchMove)
UserInputService.TouchEnded:Connect(TouchEnd)
end
TouchTapInWorld
TouchTapInWorld イベントは、ユーザーが TouchEnabled デバイスの画面に指をタッチ/タップすると発動します。ユーザーがゲームワールドをタップすると発射されます。
このイベントは、ユーザーが画面をタップして GuiObject 要素をタップしない時を判断するのに使用できます。ユーザーがGUI 要素をタップすると、UserInputService.TouchTap が TouchTapInWorld の代わりに発射します。
ユーザーのデバイスが TouchEnabled であるかどうか、およびタッチイベントが発動するかどうかをチェックするには、UserInputService.TouchEnabled を参照してください。
このイベントは、Roblox クライアントウィンドウが焦点にあるときにのみ発動します。たとえば、ウィンドウが最小化されているときに入力はキャプチャされません。
ローカルでのみ発射するため、LocalScript でのみ使用できます。
参照してください:
パラメータ
コードサンプル
local UserInputService = game:GetService("UserInputService")
local camera = workspace.CurrentCamera
local LENGTH = 500
local function createPart(position, processedByUI)
-- Do not create a part if the player clicked on a GUI/UI element
if processedByUI then
return
end
-- Get Vector3 world position from the Vector2 viewport position
local unitRay = camera:ViewportPointToRay(position.X, position.Y)
local ray = Ray.new(unitRay.Origin, unitRay.Direction * LENGTH)
local hitPart, worldPosition = workspace:FindPartOnRay(ray)
-- Create a new part at the world position if the player clicked on a part
-- Do not create a new part if player clicks on empty skybox
if hitPart then
local part = Instance.new("Part")
part.Parent = workspace
part.Anchored = true
part.Size = Vector3.new(1, 1, 1)
part.Position = worldPosition
end
end
UserInputService.TouchTapInWorld:Connect(createPart)
WindowFocusReleased
The UserInputService ウィンドウフォーカスリリースイベントは、Roblox クライアントのウィンドウが焦点を失うと発動します - 通常、Roblox クライアントがユーザーによって最小化されるとき。
たとえば、以下のコードは、Roblox クライアントが焦点を失うたびに 「ウィンドウフォーカスが解放されました」 を印刷します。
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocusReleased:Connect(function()
print("Window focus released")
end)
このイベントは、UserInputService.WindowFocused と一緒に使用して、Roblox クライアントがユーザーの画面にアクティブに焦点を合わせているかどうかを追跡できます。
ローカルでのみ発射するため、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)
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local afkEvent = ReplicatedStorage:WaitForChild("AfkEvent")
local function focusGained()
afkEvent:FireServer(false)
end
local function focusReleased()
afkEvent:FireServer(true)
end
UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)
WindowFocused
The UserInputService ウィンドウフォーカスイベントは、Roblox クライアントのウィンドウが焦点を獲得すると発動します - 通常、Roblox クライアントがユーザーの画面で最大化/アクティブに開いているときです。
たとえば、以下のコードは、Roblox クライアントが焦点を獲得するたびに 「ウィンドウが焦点になっている」 を印刷します。
local UserInputService = game:GetService("UserInputService")
UserInputService.WindowFocused:Connect(function()
print("Window focused")
end)
このイベントは、UserInputService.WindowFocusReleased と一緒に使用して、Roblox クライアントがユーザーの画面にアクティブに焦点を合わせているかどうかを追跡できます。
このイベントはローカルでのみ発動するため、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)
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)