2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity】ARでインジケータ表示

Last updated at Posted at 2022-04-09

インジケータって?

こういうの

ARで任意の場所にオブジェクトを置きたい時のターゲットインジケータってわけです。

作り方

ARFoundationを使うので、予めパッケージに追加しといて下さい。

インジケータのプレハブを用意

こういうの
スクリーンショット 2022-04-08 23.56.09.png

インジケータオブジェクトを作成

ヒエラルキーで空のオブジェクトを作成します(適当にIndicatorとか名前つける)

空のオブジェクト配下にPlaneを作成します。

スクリーンショット 2022-04-08 23.59.39.png

Planeにインジケータとして表示したいテクスチャをドラッグ&ドロップで貼り付けます。

必要なコンポーネントを追加

AR Plane ManagertとAR Raycast Managerを追加します。

スクリーンショット 2022-04-09 0.04.56.png

スクリプト作成

解説めんどくさいから全部貼ります。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;

public class PlacementIndicator : MonoBehaviour
{
    private ARRaycastManager rayManager;
    private GameObject visual;

    void Start ()
    {
        // コンポーネントを入手する
        rayManager = FindObjectOfType<ARRaycastManager>();
        visual = transform.GetChild(0).gameObject;

        // インジケーターを非表示にする
        visual.SetActive(false);
    }
    
    void Update ()
    {
        // 画面の中央からレイキャストを発射します
        List<ARRaycastHit> hits = new List<ARRaycastHit>();
        rayManager.Raycast(new Vector2(Screen.width / 2, Screen.height / 2), hits, TrackableType.Planes);

        // AR平面に当たった場合は、位置と回転を更新します
        if(hits.Count > 0)
        {
            transform.position = hits[0].pose.position;
            transform.rotation = hits[0].pose.rotation;

            // ビジュアルが無効になっている場合は有効にする
            if(!visual.activeInHierarchy)
                visual.SetActive(true);
        }
    }
}

スクリプトをIndicatorオブジェクトにアタッチ

さっき空のオブジェクトから作ったIndicatorオブジェクトに作ったスクリプトをドラッグ&ドロップしてアタッチします。

スクリーンショット 2022-04-09 0.09.48.png

おわり

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?