Hey I’m pretty new to Unity 3D & C sharp scripting. I was wondering how to stop the enemy from jittering against the player when within attacking distance (IE the enemy gets within attacking distance and stops 1 unit away) and also how do Istop the enemy from randomly moving up the screen when I press play. Here is my current script for the enemy ai
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxdistance;
public float attackTime;
public float coolDown;
private Transform myTransform;
void Awake()
{
myTransform = transform;
}
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
attackTime = 0;
coolDown = 4.0f;
}
void Update () {
Debug.DrawLine(target.position, myTransform.position, Color.red);
if (Vector3.Distance(target.position, transform.position) < 20)
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
{
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
if(attackTime > 0)
attackTime -= Time.deltaTime;
if(attackTime < 0)
attackTime = 0;
if(attackTime == 0) {
Attack();
attackTime = coolDown;
}
}
private void Attack() {
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
if(distance < 7) {
if(direction > 0) {
PlayerHealth eh = (PlayerHealth)target.GetComponent("PlayerHealth");
eh.AddjustCurrentHealth(-10);
}
}
}
}
Any help or hints will be greatly appreciated. Cheers