(スクリプト)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BotMove : MonoBehaviour
{
public Transform[] points;
private int num = 0;
private void Start()
{
// ゲーム開始時の目標地点
transform.LookAt(points[num]);
StartCoroutine(RootManager());
}
private void Update()
{
// 前進運動
transform.Translate(Vector3.forward * Time.deltaTime * 10);
}
private IEnumerator RootManager()
{
while (true)
{
// ラムダ式(ポイント)
// 目標地点に近づいたら次の目標地点に変更する
yield return new WaitUntil(() => Vector3.Distance(transform.position, points[num].transform.position) < 0.2f);
// 目標地点の変更
num = (num + 1) % points.Length;
print(num);
transform.LookAt(points[num]);
yield return new WaitForSeconds(1f);
}
}
}
(実行結果)
(スクリプトその2;OnTriggerEnterを活用するパターン)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BotMove2 : MonoBehaviour
{
public Transform[] points;
private int num = 0;
private void Start()
{
// ゲーム開始時の目標地点
transform.LookAt(points[num]);
}
private void Update()
{
// 前進運動
transform.Translate(Vector3.forward * Time.deltaTime * 10);
}
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Point"))
{
num = (num + 1) % points.Length;
transform.LookAt(points[num]);
}
}
}
(設定)