Bullet delay after shooting so you can't repeatedly shoot by clicking over and over,Wait for Bullet Counter to Reset before Shooting Again
Hi, I'm following a tutorial online for a shooter game. Bullets are delayed using a float variable, but only if you're holding down the "left-click". If you repeatedly click the left-click button as fast as you can, the bullets will leave the gun just as fast--bypassing the delay.
Is there a way to shoot ONLY if the delay counter is finished?
Here's the code! Hopefully we don't need to scrap the whole code for this. I do like the simplicity. Thanks in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunController : MonoBehaviour
{
public bool isFiring;
public BulletController bullet;
public float bulletSpeed;
public float timeBetweenShots;
private float shotCounter;
public Transform firePoint;
void Start()
{
}
void Update()
{
if (isFiring)
{
shotCounter -= Time.deltaTime;
if (shotCounter <= 0)
{
shotCounter = timeBetweenShots;
BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController;
newBullet.speed = bulletSpeed;
}
}
else
{
shotCounter = 0;
}
}
}
Answer by Hellium · Mar 27, 2020 at 10:32 PM
public class GunController : MonoBehaviour
{
public bool isFiring;
public BulletController bullet;
public float bulletSpeed;
public float timeBetweenShots;
private float nextFireTime;
public Transform firePoint;
private bool CanFire
{
get { return Time.time > nextFireTime; }
}
void Update()
{
if (isFiring && CanFire)
{
nextFireTime = Time.time + timeBetweenShots;
BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController;
newBullet.speed = bulletSpeed;
}
}
}
Thank you that worked perfectly! Thanks for cleaning up the code a bit too. Any way you could explain why this works? For me and any other newbies that may find this question?
If I have to explain my code, it means the latter was not clear enough, and that's a pity.
Basically, ins$$anonymous$$d of handling a "countdown" which is decreased each time you try to fire, I take advantage of the time naturally elapsing. nextFireTime
represents the time after which you will be able to fire again. Each time you shoot, you move timeBetweenShots
seconds later.
On the figure above, you will be able to shoot at any point in time as long as you are in the green zone (i.e, when CanFire
returns true)
Your answer
Follow this Question
Related Questions
How to scale object when timer ends? 0 Answers
Timer randomly not working. I need of assistance. C# 0 Answers
Set a delay for firing 0 Answers
script delay ("on mouseclick") 0 Answers