I have a working blaster and even written a code of limiting the firing per 5 seconds but nothing is working. The player still can fire as many times as the mouse is clicked. How can I make sure the blaster cool down after five shots are fired.
2 Answers
2I think the most basic way to deal with this kind of thing is to set up a timer in your FixedUpdate();
Every time you shoot you update another int to equal the time of the main timer. Then whenever you shoot you set a condition to make sure the main timer is x amount bigger than the shoot timer.
Code Example:
int mainTimer =0;
int shootTimer =0;
int minimumTimeToShoot = 10;
Update()
{
if (mainTimer >= shootTimer + minimumTimeToShoot)
{
//all your code to fire one shot
shootTimer = mainTimer;
}
}
FixedUpdate()
{
++mainTimer;
}
This example is not perfect as it only creates a minimum time between possible shots. If you want it to be 5 per second instead but no minimum time you will need to adjust the logic. Perhaps create a separate int to count each of the 5 shots. And then store a time for the first shot and the 5th shot, and use those numbers to determine your outcomes?
This is a sort of crude solution that I used in my first shooting game. There are probably much better options but it can work if you set it up right. Hope that helps!
Wow looks like I rushed to answer you before even fully reading and comprehending your original question my bad!
Try something like this:
int shotsFired =0;
int coolDownCountTimer = 0;
int timeToBeReady = 50;
Update()
{
if (shotsFired < 5)
{
++shotsFired;
//shoot bullet
}
}
FixedUpdate()
{
if (shotsFired >=5)
{
++coolDownCountTimer;
}
if (coolDownCountTimer >= timeToBeReady)
{
shotsFired =0;
coolDownTimer = 0;
}
}
And of course you gotta add more code for the shot being actually fired, don’t just automatically do it on Update()
Thank you for the help. I have the shooting part down, but this uses less coding than I wrote. Wow, just thank you!
Keep count of the number of shots fired. Have a bool flag that you switch off on the 5th shot. Start a timer on the 5th shot and on timer elapsed, flip flag back on. Sudocode: clipSize = 5; cooldownTime = 3f; count=0; onCooldown = false; TryToFire() if (!onCooldown) Fire() Fire() count++; if (count >= clipSize) count=0; onCooldown = true; StartCoroutine( WaitForCooldown( cooldownTime ) ) WaitForCooldown(delay) yield return new WaitForSeconds( delay ) onCooldown = false
– OP_toss