LoginSignup
8
10

More than 5 years have passed since last update.

vuforiaで出したオブジェクトに触りたい

Posted at

ARでミクちゃんに触りたいよね。
変なところではまってしまったのでそういうことをしないようにと

やり方

そんなに難しい考えじゃありません。
ARCameraからRayを飛ばすだけです。

環境

androidプロジェクトとしてやります。
PCとかでもInputの方が変わるだけでやり方は同じです。

実装

ray.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class ray : MonoBehaviour
{    Camera camera;

    // Use this for initialization
    void Start()
    {
        camera = GameObject.Find("ARCamera").GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        if (TouchJudge())
        {
            gameObject.GetComponent<Renderer>().material.color = Color.yellow;
        }
        else
        {
            gameObject.GetComponent<Renderer>().material.color = Color.red;
        }
    }

    bool TouchJudge()
    {
        int touchCount = Input.touchCount;

        if (touchCount > 0)
        {
            Debug.Log("touch");
            for (int i = 0; i < touchCount; i++)
            {
                Touch touch = Input.GetTouch(i);

                Ray ray = camera.ScreenPointToRay(touch.position);
                RaycastHit hit = new RaycastHit();

                Debug.DrawRay(ray.origin, ray.direction * 100);

                if (Physics.Raycast(ray, out hit))
                {
                    Debug.Log("hit");
                    if (hit.collider.gameObject == gameObject)
                    {
                        return true;
                    }
                }
            }
        }

        return false;
    }

これを触るオブジェクトの方に設定します。

解説

注意: cameraをMain Cameraにしない!!!(はまってたのはこれ)

TouchJudge()だけ解説
上から

  1. 1つ以上タップされてるか
  2. タップ情報を1つずつ処理
  3. タップ位置からRayを作成
  4. 何かに当たってるか
  5. 当たってるGameObjectが自分かどうか
  6. 当たってたらtrue
  7. それ以外ならfalse

です。

updateの方で当たってたら黄色、当たってなかったら赤になるようになってます。
ここにミクちゃんの動きとか入れればいいです。

おまけ

Rayを可視化

Debug.DrawRay()というのを知らなくてこれ聞いたとき感動したので使い方だけ
Rayを可視化できます。これ聞いただけでも超便利!!って感じ
使い方はDebug.DrawRay(始点, 方向)です

DrawRay.cs
Ray = new Ray(hogehoge);
Debug.DrawRay(ray.origin, ray.direction * 100);

directionに描画する距離をかけます。

PC用の判定メソッド

mouseJudge.cs
bool mouseJudge()
{
        RaycastHit hit;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit) && hit.collider.gameObject == gameObject)
        {
            return true;
        }
        else
        {
            return false;
        }
}
8
10
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
8
10