Skip to content

Instantly share code, notes, and snippets.

@IshidaGames
Created October 14, 2019 10:00
Show Gist options
  • Save IshidaGames/f0b3a95239ca939efe56ca51a1aadf39 to your computer and use it in GitHub Desktop.
Save IshidaGames/f0b3a95239ca939efe56ca51a1aadf39 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//NavMeshAgentを使うのに必要
using UnityEngine.AI;
//オブジェクトにNavMeshAgentコンポーネントを設置
[RequireComponent(typeof(NavMeshAgent))]
public class Enum : MonoBehaviour
{
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
GameObject player;
[SerializeField]float time = 0;
[SerializeField] float timeAttack = 0;
//列挙型、Actionの部分は自分で名前つける
enum Action
{
Patrol,
Chase,
Attack
}
//列挙型の名前を型にして変数を宣言する
[SerializeField] Action action = Action.Patrol;
void Start()
{
agent = GetComponent<NavMeshAgent>();
// autoBraking を無効にすると、目標地点の間を継続的に移動します
//(つまり、エージェントは目標地点に近づいても
// 速度をおとしません)
agent.autoBraking = false;
agent.speed = 1;
GotoNextPoint();
//Playerタグのオブジェクトを取得
player = GameObject.FindGameObjectWithTag("Player");
}
void GotoNextPoint()
{
// 地点がなにも設定されていないときに返します
if (points.Length == 0)
return;
// エージェントが現在設定された目標地点に行くように設定します
agent.destination = points[destPoint].position;
// 配列内の次の位置を目標地点に設定し、
// 必要ならば出発地点にもどります
destPoint = (destPoint + 1) % points.Length;
}
void Update()
{
//列挙型の定数をIf文の条件にする
if(action == Action.Patrol)
{
agent.speed = 2;
// エージェントが現目標地点に近づいてきたら、
// 次の目標地点を選択します
if (!agent.pathPending && agent.remainingDistance < 0.5f)
GotoNextPoint();
}
else if(action == Action.Chase)
{
agent.destination = player.transform.position;
agent.speed = 3.5f;
//5秒立ったらPatrolに戻る
time += Time.deltaTime;
if (time > 5)
{
action = Action.Patrol;
time = 0;
}
}
else if (action == Action.Attack)
{
agent.speed = 0f;
agent.isStopped = true;
transform.Rotate(new Vector3(0, 90, 0) * Time.deltaTime * 10, Space.World);
//1秒立ったらChaseに戻る
timeAttack += Time.deltaTime;
if (timeAttack > 1)
{
action = Action.Chase;
timeAttack = 0;
agent.isStopped = false;
}
}
}
private void OnCollisionEnter(UnityEngine.Collision collision)
{
//Patrolの時にPlayerタグのオブジェクトに当たったらChaseに
if (collision.gameObject.tag == "Player" && action == Action.Patrol)
{
action = Action.Chase;
}
//Patrolの時にPlayerタグのオブジェクトに当たったらAttackに
if (collision.gameObject.tag == "Player" && action == Action.Chase)
{
action = Action.Attack;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment