デフォルトで表示される、右手VRコントローラーにはビームが出ています。PCのマウスと同じように GetMouse() が使用できるようです。

ビームの非表示化

ビームの表示を消したい場合です。

local StarterGui = game:GetService("StarterGui")

StarterGui:SetCore("VRLaserPointerMode", 0)	         -- ビームの非表示

ビームの再表示

デフォルトではビームは表示されていますが、非表示にした後に再表示する場合です。

StarterGui:SetCore(“VRLaserPointerMode”, “Pointer”)

オブジェクトの取得

ボタンを押したときにビームが当たっているオブジェクトを取得する方法です。

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local VRService = game:GetService("VRService")
local Players = game:GetService("Players")

local mouse = Players.LocalPlayer:GetMouse()

-- ボタンを押したときに呼ばれる
local function onInputBegan(input, processed)
    if input.KeyCode == Enum.KeyCode.ButtonR2 then    -- 右のボタン2が押されたら
        if mouse.Target then  -- Target にはオブジェクトが入る
            -- そのオブジェクトの処理
        end
    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

パーツを移動させる

ビームとボタンを使って、パーツを動かす基本的なプログラムは下記のようになります。なお、DragDetector を使う方法もあります。

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local VRService = game:GetService("VRService")
local Players = game:GetService("Players")
local mouse = Players.LocalPlayer:GetMouse()

local dragPart = nil
local offset = nil

-- ボタンを押したときに呼ばれる
local function onInputBegan(input, processed)
    if input.KeyCode == Enum.KeyCode.ButtonR2 then
        local target = mouse.Target
        if target then
            dragPart = target
            offset = target.Position - mouse.Hit.p
        end
    end
end

-- ボタンを離したときに呼ばれる
local function onInputEnded(input, processed)
    if input.KeyCode == Enum.KeyCode.ButtonR2 then
        if dragPart then
            -- RemoteEventを使って、サーバー側でパーツを移動させる(A)
            dragPart = nil
        end
    end
end

mouse.Move:Connect(function()
    if dragPart then
        local newPosition = mouse.Hit.p + offset
        dragPart.Position = newPosition
        -- 他のプレーヤーにも動かしている様子を見せたい場合はここで(A) の処理を行う
    end
end)

UserInputService.InputBegan:Connect(onInputBegan)
UserInputService.InputEnded:Connect(onInputEnded)

onInputBegan 内の「if target then」だけではBaseplateも移動出来てしまうので工夫が必要です。

GetMouse() の仕様

VRで使用できるものを整理しておきます。

プロパティー

Targetビームが指している最も近い3Dオブジェクトプレイヤーが何を指しているか知るために使用
Hitビームが指している3Dワールド内の正確な位置(CFrame)オブジェクトを配置したり、何かを特定の場所に移動させるために使用
X, Yビームのスクリーン上の座標GUI要素とのインタラクションを作成するために使用
ViewportPoint3Dワールドの特定の点がスクリーン上でどこに表示されるかを返す3Dオブジェクトとのインタラクションに基づくUI要素を配置するために使用

イベント

Moveビームが動いたときに発生ビームの動きに基づいて何かをトラッキングするために使用

By schilverberch

ROBLOXでゲームを作ろう! 一緒にプログラミングを学びましょう。

コメントを残す