Question by
A1-PH4 · Jul 22, 2016 at 09:20 AM ·
c#rotationpathfollowingai problems
AI moving Backwards along path
Hi, I am having trouble with my AI enemy moving along my path. The enemies are moving along the path in the correct direction but are however (problem) rotated the wrong way - sideways and backwards rather than facing forwards.
Credit: The code is from quill18creates youtube channel as I have been following the tutorial. link: https://www.youtube.com/watch?v=b7DZo4jA3Jo
C# Code
Enemy Attached Code:
using UnityEngine; using System.Collections;
public class Enemy : MonoBehaviour {
GameObject pathGO;
Transform targetPathNode;
int pathNodeIndex = 0;
public float speed = 5f;
public float health = 1f;
public int moneyValue = 1;
// Use this for initialization
void Start () {
pathGO = GameObject.Find("Path");
}
void GetNextPathNode() {
if(pathNodeIndex < pathGO.transform.childCount) {
targetPathNode = pathGO.transform.GetChild(pathNodeIndex);
pathNodeIndex++;
}
else {
targetPathNode = null;
ReachedGoal();
}
}
// Update is called once per frame
void Update () {
if(targetPathNode == null) {
GetNextPathNode();
if(targetPathNode == null) {
// No path left
ReachedGoal();
return;
}
}
Vector3 dir = targetPathNode.position - this.transform.localPosition;
float distThisFrame = speed * Time.deltaTime;
if(dir.magnitude <= distThisFrame) {
// Node Reached
targetPathNode = null;
}
else {
// Move Towards Node
transform.Translate( dir.normalized * distThisFrame, Space.World );
Quaternion targetRotation = Quaternion.LookRotation( dir );
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, targetRotation, Time.deltaTime*5);
}
}
void ReachedGoal() {
GameObject.FindObjectOfType<ScoreManager>().LoseLife();
Destroy(gameObject);
}
public void TakeDamage(float damage) {
health -= damage;
if(health <= 0) {
Die();
}
}
public void Die() {
GameObject.FindObjectOfType<ScoreManager>().money += moneyValue;
Destroy(gameObject);
}
}
Enemy Spawner Code:
using UnityEngine; using System.Collections;
public class EnemySpawner : MonoBehaviour {
float spawnCD = 0.25f;
float spawnCDremaining = 5;
[System.Serializable]
public class WaveComponent {
public GameObject enemyPrefab;
public int num;
[System.NonSerialized]
public int spawned = 0;
}
public WaveComponent[] waveComps;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
spawnCDremaining -= Time.deltaTime;
if(spawnCDremaining < 0) {
spawnCDremaining = spawnCD;
bool didSpawn = false;
// Go through the wave comps until we find something to spawn;
foreach(WaveComponent wc in waveComps) {
if(wc.spawned < wc.num) {
// Spawn it!
wc.spawned++;
Instantiate(wc.enemyPrefab, this.transform.position, this.transform.rotation);
didSpawn = true;
break;
}
}
if(didSpawn == false) {
if(transform.parent.childCount > 1) {
transform.parent.GetChild(1).gameObject.SetActive(true);
}
else {
}
Destroy(gameObject);
}
}
}
}
Please Help,
Comment