(ポイント)
・List(リスト)の使い方・・・動的配列
・2点間の距離の求めかた・・・Vector3.Distance( )関数
・カウントを1ずつあげてループさせる方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PointMaker : MonoBehaviour {
public GameObject pointPrefab;
public AudioClip setSound;
// ★ポイント
// List(リスト)の宣言(配列を動的に扱うことができる)
// 要素の数を動的に増減することができる。
private List<GameObject> pointList = new List<GameObject>();
private NavMeshAgent agent;
private int destNum = 0;
void Start()
{
agent = GetComponent<NavMeshAgent>();
GoToNextPoint();
}
void Update () {
if(Input.GetKeyDown(KeyCode.Z)){
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit)){
GameObject target = hit.collider.gameObject;
if(target.tag == "Ground"){
GameObject point = (GameObject)Instantiate(pointPrefab, hit.point, Quaternion.identity);
AudioSource.PlayClipAtPoint(setSound, Camera.main.transform.position);
// 生成したオブジェクををリストに加える。
pointList.Add(point);
}
}
}
// ★確認用
//print("要素数" + pointList.Count + "個");
//print("destNumの番号" + destNum);
//print(pointList[pointList.Count - 1].transform.position);
// ★2点間(プレーヤーと最終チェックポイント間)の距離を求める。
float distance = Vector3.Distance(transform.position, pointList[pointList.Count - 1].transform.position);
print(distance);
if(distance < 1.0f){
agent.enabled = false;
}
if(agent.remainingDistance < 1.5f){
GoToNextPoint();
}
// ★セクションポイント配置後、Gボタンを押すとプレーヤーが動き出す。
if(Input.GetKeyDown(KeyCode.G)){
agent.enabled = true;
}
}
void GoToNextPoint(){
if(pointList.Count == 0){
return;
}
agent.destination = pointList[destNum].transform.position;
destNum = (destNum + 1) % pointList.Count;
}
}