Skip to content

Instantly share code, notes, and snippets.

@TheCuttlefish
Created May 11, 2018 20:35
Show Gist options
  • Save TheCuttlefish/9b8a64ef6eec085535a0239540ca20fd to your computer and use it in GitHub Desktop.
Save TheCuttlefish/9b8a64ef6eec085535a0239540ca20fd to your computer and use it in GitHub Desktop.
Enemy patrol AI
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAI : MonoBehaviour {
public List<Transform> patrolPos = new List<Transform>();
public int posIndex = 0;
public float speed = 0.3f;
public float rotSpeed = 0.2f;
bool look = true;
public int waitTime = 30;
void Start () {
}
void Update () {
Movement ();
}
void Movement(){
if(look == true){
ChangeRot ();
}else{
Walk ();
}
}
void Walk(){
transform.position = Vector3.MoveTowards (transform.position, patrolPos[posIndex].position, speed);
if (Vector3.Distance (transform.position, patrolPos [posIndex].position) < 0.5f) {
posIndex++;
posIndex = posIndex % patrolPos.Count;
look = true;
}
}
float zRot;
int lookTimer = 0;
void ChangeRot(){
//rotation logic
float AngleRad = Mathf.Atan2 ( patrolPos [posIndex].position.y - transform.position.y, patrolPos [posIndex].position.x - transform.position.x);
float angle = (180 / Mathf.PI) * AngleRad;
zRot = Mathf.LerpAngle(zRot,angle,rotSpeed);
transform.localEulerAngles= new Vector3(0,0, zRot);
//timer logic
if (look) {
lookTimer++;
if (lookTimer > waitTime) {
lookTimer = 0;
look = false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment