Hi,
I am trying to find the most simple possible way to make an enemy face the player and then shoot. I have pretty much got this sorted through various videos etc however when the enemy shoots it does so about 20 times a second. I would like to know a way of making it shoot 1 bullet per second or maybe even better slightly random timings but with space between the bullets. You can probably tell I am just learning but have tried to find out the answer but would have to change all I have done to use it. I think I am close so any help would be great
var target:Transform;
//create a variable to check how far away enemy is
var range = 10.0;
var shotPrefab:Transform;
function Update()
{
if (CanAttackTarget())
{
var targetRotation = Quaternion.LookRotation(target.position - transform.position, Vector3.up);
//this code rotates the object. Needs current rotation, target and then a delay. Delta time is difference between last frame rendered and current frame rendering
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0);
InvokeRepeating("shoot", 2, 2);
}
}
function CanAttackTarget()
{
if (Vector3.Distance(transform.position, target.position) > range)
{
return false;
}
var hit: RaycastHit;
//line cast detects a collider within cast
//this code means that you can hide behind walls etc
if (Physics.Linecast(transform.position, target.position, hit))
{
if (hit.collider.gameObject.tag != "Player")
{
print ("Item in the way");
return false;
}
else
{
print("Player detected");
return true;
}
}
return true;
}
function shoot()
{
var shot = Instantiate(shotPrefab, transform.position, Quaternion.identity);
shotPrefab.rigidbody.AddForce(transform.forward * 2000);
}
Thanks