- Home /
How do I set a fire rate for my enemy shooting?
Hello! I'm working on a 2D platform game and I'm having trouble setting time restrictions for my rate of shooting. I would like a bullet to be shot out by the enemy every 1 second but instead I get a continuous stream of bullets from the enemy when player is in range. How can I fix this?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class enemy_move : MonoBehaviour {
//Moving
public float MoveSpeed;
public int MaxDist;
//Shooting
public Rigidbody2D bulletPrefab;
public Transform LSpawn;
public Transform RSpawn;
public Vector2 speed;
Rigidbody2D rb2d;
//All
public Transform target;
public int radius;
bool inRadius;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
rb2d.velocity = speed;
}
void Update()
{
EnemyMove();
if (inRadius)
{
EnemyShoot();
}
}
public void EnemyMove()
{
float distFromTarget = Vector2.Distance(transform.position, target.position);
if (distFromTarget <= radius)
{
inRadius = true;
}
else
{
inRadius = false;
}
//MOVES ENEMY TOWARDS TARGET
if (inRadius && distFromTarget > MaxDist)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, MoveSpeed);
}
}
public void EnemyShoot()
{
float DistfromSpawnL = Vector2.Distance(LSpawn.position, target.position);
float DistfromSpawnR = Vector2.Distance(RSpawn.position, target.position);
if (DistfromSpawnL < DistfromSpawnR )
{
Rigidbody2D BulletInstance = Instantiate(bulletPrefab, LSpawn.position, LSpawn.rotation);
BulletInstance.velocity = speed;
}
if (DistfromSpawnR < DistfromSpawnL)
{
Rigidbody2D BulletInstance = Instantiate(bulletPrefab, RSpawn.position, RSpawn.rotation);
BulletInstance.velocity = speed;
}
}
}
Answer by Rexro · Mar 21, 2018 at 02:33 AM
You can add a public float, I will call it time. At the top of the Update()
you can add this in:
public float time;
private void Update()
{
time += Time.deltaTime;
if(time >= 1)
{
time = 0;
if (inRadius)
{
EnemyShoot();
}
}
}
Time.deltalTime is the time between the function being called last. So adding it to time will show the time in seconds from the last time it was set to 0. The if statement will check if the time passed is greater or equal to 1 second, and if so, your function will be called, and time is set back to 0 to restart the process.
Your answer
![](https://koobas.hobune.stream/wayback/20220612155020im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rate of health loss in trigger box. 1 Answer
Enemy shooting player driving me crazy! 2 Answers
Enemy shoot at player in 2D game 3 Answers
trying to regulate character speed. 1 Answer
Enemy AI problem 1 Answer