
マーカーを自動的にトラッキングするにはどうしたらいいですか?

タグを追加して順番にオブジェクトを認識させる方法があります。
完成イメージ
下準備
以下の流れで作業を進めていきます。
- Projectを開く
- オブジェクト[Cube]×2 と[Sphere]×5 を配置
- オブジェクト[Cube]×2 と[Sphere]×5 に色を追加
- オブジェクト[Cube]にScriptを追加
▼ここでの操作方法に不安のある方は、こちらをご参照ください▼
完成イメージは以下のようになります。(具体的なパラメータは以下で解説)
マウスがチーズを順番にトラッキングするイメージで作成しました。

オブジェクトの配置
解説画面と合わせるために、以下のように各オブジェクトの配置や名前を変更していきます。
[Cube]は、オブジェクト名を[Ground]に変更し、[Transform]を以下のように変更します。

同じく[Cube]は、オブジェクト名を[Mouse]に変更し、[Transform]を以下のように変更します。Script名は、[Mouse_move]にします。

[Sphere]は、オブジェクト名を[Cheese]に変更し、[Transform]を適当な位置に配置します。

残りの4つの[Cheese]を作成します。Hierarchyウインドウの[Cheese]をProjectウインドウにドラックしてプレハブ化してから複製します。このようにすると変更等がある場合に便利です。
複製すると以下のようになります。

[Main Camera]は、Inspectorウインドウの[Transform]を以下のように変更します。

Tagの追加
トラッキングの対象となる[Cheese]にTagを設定します。このTagを使って、Scriptで制御していきますので、その準備です。
Hierarchyウインドウで[Cheese]を選択し、Inspectorウインドウで、[Tag]のプルダウンメニューをクリックして、[Add Tag…]>[+]をクリックして、[Cheese]という名前のタグを作成します。

作成したTagをプルダウンメニューから選択してセットします。

Scriptの追加
[Mouse]が[Cheese]をトラッキングするためのScriptを追加します。
Cheeses.Lengthで要素数を取得し、CheeseCountと比較して移動を制御します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mouse_move : MonoBehaviour
{
public GameObject[] Cheeses;
int CheeseCount = 0;
public float speed = 1.0f;
public float nearly = 1.0f;
public float rotSpeed = 1.0f;
void Start()
{
//CheeseというTag名のゲームオブジェクトを取得
Cheeses = GameObject.FindGameObjectsWithTag("Cheese");
}
void Update()
{
if (Cheeses.Length == 0) return;
Vector3 lookAtTarget = new Vector3
(Cheeses[CheeseCount].transform.position.x,
this.transform.position.y,
Cheeses[CheeseCount].transform.position.z);
Vector3 direction = lookAtTarget - this.transform.position;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction),
Time.deltaTime * rotSpeed);
//目標物とのベクトルの長さとnearly(閾値)を比較
if(direction.magnitude < nearly)
{
CheeseCount++;
if(CheeseCount >= Cheeses.Length)
{
CheeseCount = 0;
}
}
this.transform.Translate(0, 0, speed * Time.deltaTime);
}
}
編集が完了したら、保存します。
Tagの認識
Scriptに、5つの[Cheese]のTagを認識させます。
Hierarchyウインドウの[Mouse]を選択して、InspectorウインドウのScript>[Cheeses]の下の[+]をクリックして、[Cheese]、[Cheese(1)]・・・[Cheese(4)]と順番に追加します。


完了すると、以下のようになります。

これで、Scriptは完了です。
動作確認
[▶︎]ゲームプレイをクリックして、動作を確認します。
[Cheese]を順番に回っていくScriptが完成しました。