AI Attacks way to fast

Good day (first post on these forums :smile:).

I’m working on a very small game (what game doesn’t really matter). My opponents shoot at me when they get into range (that’s what I have this script for):

var attackInterval = 3;
var bullet : Rigidbody;
var bulletSpeed = 20;
var ammoCount = 100;
var ammoCost = 1;
var minDist = 15;
var hasAmmo : boolean = false;
var withinRange : boolean = false;
var APCollider : Collider;
var spaceshipTransform : Transform;

function Update () {
	if(ammoCount < 0) {
		ammoCount = 0; // negative ammo isn't possible, also needed for checkAmmo()
	}
	checkAmmo();
	
	checkRange();
	if(withinRange) {
		Attack();
		ammoCount -= ammoCost;
	}
}

function Attack() { 
	while (hasAmmo) {
		Shoot();
		yield WaitForSeconds (attackInterval);
	}
}

function checkAmmo() {
	if(ammoCount > 0) {
		hasAmmo = true;
	}
	else if(ammoCount == 0) {
		hasAmmo = false;
	}
}

function checkRange() {
	if (spaceshipTransform) {
		var dist = Vector3.Distance(spaceshipTransform.position, transform.position);
	}
	
	if (dist < minDist) {
		withinRange = true;
	}
	else {
		withinRange = false;
	}
}

function Shoot() {
	var instantiatedProjectile : Rigidbody = Instantiate(bullet, transform.position, transform.rotation );
	instantiatedProjectile.velocity = transform.TransformDirection( Vector3( 0, 0, bulletSpeed ) );
	Physics.IgnoreCollision( instantiatedProjectile.collider, transform.root.collider );
	Physics.IgnoreCollision( instantiatedProjectile.collider, APCollider );
}

However, it sprays the bullets all over the place and yield in Attack() doesn’t work. What is wrong?

Try adding a timer to your attack function:

private var LastShot = 0.0;

if (Time.time > LastShot + 1.00 )
{
//Shoot your brains out --- All of your shooting code
LastShot = Time.time;
}

This should slow down your bot from spraying bullets. So in effect it should look something like this:

function Attack() {
   while (hasAmmo) {
     if (Time.time > LastShot + 1.00 )
     {
      Shoot(); 
      LastShot = Time.time;
     }
   }
}

Thanks for the reply, I’ll try it out (unity just stopped responding…)

Edit: apparently the script is making unity crash when I press play. Let me see if I typed any errors.

Make sure you’re not forgetting the private variable (or the variable in any case) Otherwise “LastShot” won’t work.

I’ve tried several things, but it still doesn’t work. :s I have to end the process of Unity after clicking play

Since Attack is a coroutine, you don’t need to call it repeatedly in the Update function. Call Attack once in the Start function and check if the target is in range during the coroutine loop:-

function Attack() { 
   while (hasAmmo) {
      if (withinRange) { 
         Shoot(); 
      }

      yield WaitForSeconds (attackInterval);
   }
}