VRコントローラーのビーム
VRのポインター表示を切り替え、指したパーツや座標を取得する例です。
このページの目次
ビームの非表示化
StarterPlayer → StarterPlayerScripts のLocalScriptで、VRのポインターを非表示にします。
local VRService = game:GetService("VRService")
VRService.LaserPointer = Enum.VRLaserPointerMode.Disabled
ビームの再表示
デフォルトではビームは表示されていますが、非表示にした後に再表示する場合です。
VRService.LaserPointer = Enum.VRLaserPointerMode.Pointer
オブジェクトの取得
ボタンを押したときにビームが当たっているオブジェクトを取得する方法です。
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local mouse = Players.LocalPlayer:GetMouse()
-- ボタンを押したときに呼ばれる
local function onInputBegan(input, processed)
if not processed and input.KeyCode == Enum.KeyCode.ButtonR2 and mouse.Target then
print(mouse.Target.Name, mouse.Hit.Position)
end
end
UserInputService.InputBegan:Connect(onInputBegan)
座標の取得
座標は上記 mouse の Hit プロパティに入ります。Hit は CFrame 型です。
local function onInputBegan(input, processed)
if input.KeyCode == Enum.KeyCode.ButtonR2 then -- 右のボタン2が押されたら
local cframe = mouse.Hit
print(cframe)
end
end
パーツを移動させる
Workspace に VRTargets というFolderを作り、移動させたい固定済みのPartをその直下に入れます。次のLocalScriptで、右トリガーを押しながら指す方向を変えると、選んだPartが動きます。DragDetectorを使う方法もあります。
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local mouse = Players.LocalPlayer:GetMouse()
local targets = workspace:WaitForChild("VRTargets")
local dragPart = nil
local offset = nil
-- ボタンを押したときに呼ばれる
local function onInputBegan(input, processed)
if not processed and input.KeyCode == Enum.KeyCode.ButtonR2 then
local target = mouse.Target
if target and target.Parent == targets then
dragPart = target
offset = target.Position - mouse.Hit.Position
end
end
end
-- ボタンを離したときに呼ばれる
local function onInputEnded(input, processed)
if input.KeyCode == Enum.KeyCode.ButtonR2 then
dragPart = nil
end
end
mouse.Move:Connect(function()
if dragPart then
local newPosition = mouse.Hit.Position + offset
dragPart.Position = newPosition
end
end)
UserInputService.InputBegan:Connect(onInputBegan)
UserInputService.InputEnded:Connect(onInputEnded)
この例の移動結果は自分の画面に反映されます。サーバーで対象と距離を確認してから全員の画面へ反映する方法は、VRゲームの作成で扱います。コントローラーが向く方向を直接調べたい場合も、同じ講座の VRService と Raycast の例を参照してください。
GetMouse() の仕様
VRで使用できるものを整理しておきます。
プロパティ
| プロパティ | 取得できる値 |
|---|---|
Target |
ポインターが指しているパーツ。見つからなければ nil |
Hit |
ポインターが指している位置と向き(CFrame)。位置だけなら Hit.Position |
X と Y |
画面上のポインターの座標 |
イベント
| Move | ビームが動いたときに発生 | ビームの動きに基づいて何かをトラッキングするために使用 |
動作を確かめる
まず表示切り替えだけを試し、次にパーツを指したときに得られる対象と座標を確かめます。