Created
September 21, 2019 12:05
-
-
Save IshidaGames/fbbc61a2a88ec418ca4b5ba6a3383ca1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
//NavMeshAgent使うときに必要 | |
using UnityEngine.AI; | |
//オブジェクトにNavMeshAgentコンポーネントを設置 | |
[RequireComponent(typeof(NavMeshAgent))] | |
//衝突を判定するためにRigidbodyコンポーネントを設置 | |
[RequireComponent(typeof(Rigidbody))] | |
public class Player : MonoBehaviour | |
{ | |
private GameObject nearObj; | |
private NavMeshAgent agent; | |
void Start() | |
{ | |
agent = GetComponent<NavMeshAgent>(); | |
//TargetのTagのオブジェクトで一番近いものを返す | |
nearObj = serchTag(gameObject, "Target"); | |
//NavMeshAgentの目的地を一番近いTargetタグのオブジェクトの位置にする | |
agent.destination = nearObj.transform.position; | |
} | |
GameObject serchTag(GameObject nowObj, string tagName) | |
{ | |
//一時的に距離を入れる変数 | |
float tmpDis = 0; | |
//一番近いオブジェクトの距離を入れる変数 | |
float nearDis = 0; | |
//対象となるオブジェクトを入れる変数 | |
GameObject targetObj = null; //オブジェクト | |
//タグ指定されたオブジェクトを配列で取得する | |
foreach (GameObject obs in GameObject.FindGameObjectsWithTag(tagName)) | |
{ | |
//自身と取得したオブジェクトの距離を取得 | |
tmpDis = Vector3.Distance(obs.transform.position, nowObj.transform.position); | |
//オブジェクトの距離が一番近いか、距離0であるものを決める | |
if (nearDis == 0 || nearDis > tmpDis) | |
{ | |
nearDis = tmpDis; | |
targetObj = obs; | |
} | |
} | |
return targetObj; | |
} | |
private void OnTriggerEnter(Collider other) | |
{ | |
//Targetタグのオブジェクトに衝突したら実行 | |
if (other.gameObject.tag == "Target") | |
{ | |
//ぶつかったオブジェクトを消す | |
Destroy(other.gameObject); | |
//0.1秒後にNewTarget関数を実行 | |
Invoke("NewTarget", 0.1f); | |
} | |
} | |
private void NewTarget() | |
{ | |
//再び一番近いTargetオブジェクトを求める | |
nearObj = serchTag(gameObject, "Target"); | |
agent.destination = nearObj.transform.position; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment