Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
DMD2542-Project4-AndrewSides/Final Platformer/Assets/Scripts/EnemyAI.cs
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
85 lines (65 sloc)
2.36 KB
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; | |
using Pathfinding; | |
public class EnemyAI : MonoBehaviour | |
{ | |
public Transform target; //target of object | |
public float speed = 200f; //speed of object | |
public float nextWayPointDistance = 3f; //will tell object to find next waypoint | |
Path path; //current path following | |
int currentWaypoint = 0; //current waypoint of the path that it's following | |
bool reachedEndofpath = false; //if it has reached the last waypoint | |
Seeker seeker;//reference to a seeker script that lets enemy find player | |
Rigidbody2D rb; | |
public Transform enemyGFX; | |
void Start() | |
{ | |
seeker = GetComponent<Seeker>(); //gets the component called seeker | |
rb = GetComponent<Rigidbody2D>(); //gets the rigidbody component | |
InvokeRepeating("UpdatePath", 0f, .5f); //repeats process every time | |
} | |
void UpdatePath() | |
{ | |
if (seeker.IsDone()) | |
seeker.StartPath(rb.position, target.position, OnPathComplete); //allows script to constantly create a path for the object | |
} | |
void OnPathComplete(Path p) //determines if creating the path is complete or not | |
{ | |
if(!p.error) | |
{ | |
path = p; | |
currentWaypoint = 0; | |
} | |
} | |
void FixedUpdate() //checks if it reached the end of the path | |
{ | |
if (path == null) | |
return; | |
if (currentWaypoint >= path.vectorPath.Count) | |
{ | |
reachedEndofpath = true; | |
return; | |
} | |
else | |
{ | |
reachedEndofpath = false; | |
} | |
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized; //sets the direction of the object | |
Vector2 force = direction * speed * Time.deltaTime; //adds force to the object | |
rb.AddForce(force); | |
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]); | |
if (distance < nextWayPointDistance) | |
{ | |
currentWaypoint++; | |
} | |
if (rb.velocity.x >= 0.01f) //flips the object when the player goes to the other side of the game object | |
{ | |
enemyGFX.localScale = new Vector3(-1f, 1f, 1f); | |
} | |
else if (rb.velocity.x <= -0.01) | |
{ | |
enemyGFX.localScale = new Vector3(1f, 1f, 1f); | |
} | |
} | |
} |