- Home /
Random enemy fire rate
Hello guys, I'm trying to make a school project (space invader) and I have a itty problem with my alien shooting
I want them to shoot at a random rate, I more o less managed to do that I think... Problem is I don't know why, at the beginning of the game they all shoot once, all together. How do I make the random shooting start at the same time the game does?
Second, sometime the random make too many bullet pop at once. Is there a way to limit the possible number of alien bullets?
script is this
using UnityEngine;
using System.Collections;
public class canonenemy : MonoBehaviour {
public GameObject bolt;
public Transform Canon;
public float fireRatep;
public float fireRatem;
private float nextFire = 3.0f;
// Update is called once per frame
void FixedUpdate () {
if (Time.time > nextFire) {
nextFire = Time.time + Random.Range (fireRatep, fireRatem);
Instantiate (bolt, Canon.position, Canon.rotation);
}
}
}
Thanks in advance! ^^
Ok, thanks a lot, my first problem is now solved. The second one, I explain better, is that I'd like to have a certain number of enemy bullet on screen at the same time.
Like no more than 5 enemy bullets, present at the same time, but I have no idea how to tell Unity to do that...
Answer by BabilinApps · Dec 27, 2014 at 07:58 PM
It's because the value of
`private float nextFire = 3.0f;`
starts at 3 for all of the enemies. Try adding:
`nextFire = nextFire + Random.Range (fireRatep, fireRatem);`
to your start function to offset all of the start times by the random range.
Best luck to you!
Answer by Steffen D E · Dec 27, 2014 at 07:58 PM
I think your problems lie in FixedUpdate and in next fire.
FixedUpdate is called independetly of framerate, so if you use Update instead, I think that should fix the douple fireing.
For everyone firing at one, is because they are all set to fire 3 sec. after start (nextFire = 3).
you can fix this by using:
void Start()
{
nextFire = Time.time + Random.Range (fireRatep, fireRatem);
}
hope this fixes it :)
Answer by troien · Dec 27, 2014 at 05:14 PM
The reason why hey fire at the same time at the start is because you set nextfire to a fixed value at the start (3.0f), and then after they fired once, you set it to a random value.
You probably want to set it to a random value at the start. Like this:
private void Start()
{
nextFire = Time.time + Random.Range(fireRatep, fireRatem);
}
Your second problem is a bit vague. Do you mean that one cannon spaws its bullets to fast after each other sometimes? (If so, increase fireRatep. As this is the minimum time in secs between spawning bullets, while fireRatem is the maximum time in seconds between the spawning of bullets)
Answer by chillandcodegames · Aug 04, 2021 at 08:14 AM
This is what I have used and it works awesome.
fireInterval = Random.Range(1,20);
if (playerAlive){
if (Time.time > nextFire)
{
shoot();
nextFire += fireInterval/3;
}
}