i have an enemy that follows the player, but when the character is far away enough from it, it stops moving and starts twitching.
using UnityEngine;
using System.Collections;
public class ExperimentalEnemy : MonoBehaviour {
public Transform target;
public Transform Bullet;
public int moveSpeed;
public int rotationSpeed;
public float maxDistance = 50f;
public int HitBoxRadius;
public ExperimentalDeath Damage;
public GameObject MonstercatChar;
public float Health = 10f;
private Transform myTransform;
public GameObject Char;
public Animator Enemy;
public GameObject Poof;
void Awake() {
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
GameObject Go2 = GameObject.FindGameObjectWithTag("Bullet");
Bullet = Go2.transform;
Char = GameObject.FindGameObjectWithTag("Player");
maxDistance = 20f;
HitBoxRadius = 4;
//Reference to DamageChar from the ExperimentalDeath.cs script
Component Damage = Char.GetComponent();
}
// Update is called once per frame
void Update () {
if (Health < 0.1) {
EnemyDie ();
}
Debug.DrawLine(target.position, myTransform.position, Color.blue);
//Look at target
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
if(Vector3.Distance(target.position, myTransform.position) < HitBoxRadius) {
Damage.DamageChar(Random.Range(0.01F, 0.2F));
Debug.Log ("Is Damaging " + Char);
}
if(Vector3.Distance(Bullet.position, transform.position) < HitBoxRadius) {
EnemyDamage(Random.Range(0.01F, 0.2F));
Debug.Log ("Is Damaging Enemy By" + Bullet);
}
}
public void EnemyDamage (float amount) {
Health -= amount;
}
public void EnemyDie () {
Instantiate (Poof, transform.position, Quaternion.Euler(0f, 0f, Random.Range(0f, 360f)));
Destroy (gameObject, 5);
Enemy.SetBool ("Die", true);
}
void onTriggerEnter (Collider other){
if (other == GameObject.FindGameObjectWithTag ("Bullet")){
Destroy (other);
EnemyDamage(Random.Range(0.01F, 0.2F)) ;
Debug.Log ("Bullet In Range");
Debug.Log ("Object in Range");
}
}
}
↧