Hi guys,
I’m using the MultiTargetFree.cs script and was wondering how would I implement (move) the AI using the path to the target?
Hi guys,
I’m using the MultiTargetFree.cs script and was wondering how would I implement (move) the AI using the path to the target?
This is what I have so far:
`using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
[RequireComponent(typeof(AudioSource))]
[RequireComponent(typeof(CharacterController))]
[AddComponentMenu(“Pathfinding/AI/AIPath (generic)”)]
public class AITargetPlayer : MonoBehaviour {
/* The possible target objects */
public GameObject[] PlayerTarget;
private Transform TargetPlayer;
private Transform EnemyTrans;
/* The paths currently being calculated or have been calculated */
private Path[] lastPaths;
/* Number of paths completed so far */
private int numCompleted = 0;
/* The calculated best path */
private Path bestPath = null;
private Path attackDistance;
private float twenty = 20f;
private float ten = 10f;
private float five = 5f;
public AudioClip Growl;
private AudioSource Roar;
private float clipEnd;
private float clipAniEnd;
private bool beingAttacked = false;
private bool chase = false;
private bool playedGrowl = false;
private int sx = 0;
public float moveSpeed;
public float rotationSpeed;
void Awake() {
EnemyTrans = transform;
}
/* Searches for the Player Target */
void Start () {
if (PlayerTarget.Length == 0){ // if no waypoints, find them
PlayerTarget = GameObject.FindGameObjectsWithTag("Player"); // Find Player Waypoints
}
if(TargetPlayer == null) {
GameObject TarP = GameObject.FindGameObjectWithTag("Player"); //Target Player
TargetPlayer = TarP.transform;
}
SearchClosest();
}
/* Call to update the bestPath with the closest path one of the targets.
* It will take a few frames for this to be calculated, the bestPath variable will be null in the meantime
*/
public void SearchClosest () {
//If any paths are currently being calculated, cancel them to avoid wasting processing power
if (lastPaths != null)
for (int i=0;i<lastPaths.Length;i++)
lastPaths[i].Error ();
//Create a new lastPaths array if necessary (can reuse the old one?)
if (lastPaths == null || lastPaths.Length != PlayerTarget.Length) lastPaths = new Path[PlayerTarget.Length];
//Reset variables
bestPath = null;
numCompleted = 0;
//Loop through the targets
for (int i=0;i<PlayerTarget.Length;i++) {
//Create a new path to the target
ABPath p = ABPath.Construct (transform.position,PlayerTarget[0].transform.position, OnTestPathComplete);
/* Before version 3.2
Path p = new Path (transform.position,targets[i].position, OnTestPathComplete);
*/
lastPaths[i] = p;
//Request the path to be calculated, might take a few frames
//This will call OnTestPathComplete when completed
AstarPath.StartPath(p);
}
}
/* Called when each path completes calculation */
public void OnTestPathComplete (Path p) {
if (p.error) {
Debug.LogWarning ("One target could not be reached!\
"+p.errorLog);
}
//Make sure this path is not an old one
for (int i=0;i<lastPaths.Length;i++) {
if (lastPaths[i] == p) {
numCompleted++;
if (numCompleted >= lastPaths.Length) {
CompleteSearchClosest ();
}
return;
}
}
}
/* Called when all paths have completed calculation */
public void CompleteSearchClosest () {
//Find the shortest path
Path shortest = null;
float shortestLength = float.PositiveInfinity;
//Loop through the paths
for (int i=0;i<lastPaths.Length;i++) {
//Get the total length of the path, will return infinity if the path had an error
float length = lastPaths[i].GetTotalLength();
if (shortest == null || length < shortestLength) {
shortest = lastPaths[i];
shortestLength = length;
}
}
Debug.Log ("Found a path which was " + shortestLength + " long");
bestPath = shortest;
attackDistance = shortest;
}
private void CheckAttackDistance() {
if (attackDistance.GetTotalLength() < twenty) {
beingAttacked = true;
}
}
public void FixedUpdate () {
//Highlight the best path in the editor when it is found
if (bestPath != null && bestPath.vectorPath != null) {
for (int i=0;i<bestPath.vectorPath.Count-1;i++) {
Debug.DrawLine (bestPath.vectorPath[i],bestPath.vectorPath[i+1],Color.red);
}
/* Before version 3.2
for (int i=0;i<bestPath.vectorPath.Length-1;i++) {
*/
SearchClosest();
if (attackDistance.GetTotalLength() < twenty) {
beingAttacked = true;
}
}
if(beingAttacked == true) {
GetComponent<EnemyAI>().enabled = false;
//Look at target
EnemyTrans.rotation = Quaternion.Slerp(EnemyTrans.rotation, Quaternion.LookRotation(TargetPlayer.position - EnemyTrans.position), rotationSpeed * Time.deltaTime);
//Vector3 desiredVelocity = EnemyTrans.TransformDirection(Vector3.forward);
if(Time.time > clipAniEnd && sx < 2) { // if previous animation not playing anymore...
animation.Stop("walk_loop");
animation.Play("Roar");
audio.volume = 0.5f;
audio.PlayOneShot(Growl); // play the new one...
clipAniEnd = Time.time + animation["Roar"].length;
sx++;
beingAttacked = false;
}
if(sx == 2 && clipAniEnd < Time.time) {
if(beingAttacked == false) {
animation.Stop ();
}
if (attackDistance.GetTotalLength() >= five) {
CharacterController controller = GetComponent<CharacterController>();
animation.Play ("Run");
//Move towards target
//controller.SimpleMove(desiredVelocity * moveSpeed);
//Direction to the next waypoint
Vector3 dir = (TargetPlayer.position-EnemyTrans.position).normalized;
dir *= moveSpeed;// * Time.deltaTime;
controller.SimpleMove (dir);
}
}
}
}
}`
I have the monster/enemy following the player but not by the path. Also when the player goes round a wall the monster gets stuck facing the wall and will not go round it.