how would i set up a gun that shoots for 3 seconds, then pauses to cool down before it can shoot again?
I'm try to set up a gun that fires a certain amount of shots, then has to cool down before you can start shooting again.
Answer by JVene · Jun 28, 2018 at 02:45 AM
First, the simple case:
In Update (or FixedUpdate, whatever you're using)
Store the return from Time.time in your script's object at the moment the user begins firing the gun. Ensure this is at the start of firing (so you're not resetting this value every update). I like using bools to indicate such a state change, as in "hasFiringStarted" is false until the first trigger press - set it to true, and skip taking a starting time sample when it is true.
When "hasFiringStarted" is true, during update, check the difference between the current time and the start time, as in float dt = Time.time - StartOfFiringTime; When dt >= 3.0f, it's been 3 seconds.
When that happens, you'll need to set some state value that indicates the gun is hot. Perhaps a bool "isGunHot" is set true when dt >= 3.0f. You'll also need to note the time this happens, as in "gunStartsCooling = Time.time;
Now, you repeat about the same thing for gun cooling. How long does the gun have to cool? While gunStartsCooling is true, check the float dt Time.time - gunStartsCooling; when dt >= cooling wait time, you can set "isGunHot" to false.
Now, back toward the gun trigger logic, you inhibit firing if "isGunHot" is true. When it's false, you can fire.
The above can be extended for the not so simple case:
Ins$$anonymous$$d of time, consider temperature. You could add to some temperature value for every fire. Subtract for it during non-firing time (use factors from Time.deltaTime (or Time.fixedDeltaTime if you use FixedUpdate) to control how fast heat drains out of the gun. When it's too hot, inhibit firing.
In this way you're not just limiting a fire of 3 seconds. You're also inhibiting firing if someone fires several 1 second bursts in a row.
Your answer
Follow this Question
Related Questions
Cooldown/Countdown not working as expected 0 Answers
how to add shoot cooldown 1 Answer
Stamina disabled but still registering extra click 0 Answers
Machine Gun shooting 1 Answer