- Home /
C# RayCast Fire Cooldown DeltaTime Help
Hello community,
I'm looking for some assistance on a C# script I am writting. I have a gattling gun that uses RayCasting for firing. I'm utilizing a custom cooldown system, but am having difficulty with the scripting to make it frame-rate-independent. I realize this is done by multiplying in the Time.DeltaTime, however the exact maths escape me. Can someone possibly assist? Here is what I have (with everything but the cooldown system ripped out):
void Update () { //TURRET ROTATION SCRIPTS HERE
//Handle the input commands
HandleActionInput();
//Decrement the Cooldowns if they are above 0.0
if (cd_GattlingCooldown > 0) cd_GattlingCooldown -= cd_GattlingRecovery;
}
void HandleActionInput() { if (Input.GetButton("Fire1")) { if (cd_GattlingCooldown <= 0) Fire(); } }
void Fire()
{
cd_GattlingCooldown += cd_Gattling;
GattlingRayCast();
}
cd_GattlingCooldown is set to 0. This is decremented until 0 by the cd_GattlingRecovery (1f) on each Update cd_Gattling is total cooldown time applied when Gattling is fired (20f)
This is working great and I like the numbers as they are, but I'm trying to incorporate Time.DeltaTime to make it so framerates do not effect fire rate.
Does anyone with a stronger handle on maths able to assist me? Thank you in advance!
Answer by aldonaletto · May 19, 2012 at 11:45 PM
You can just subtract Time.deltaTime from cd_GattlingCooldown each Update: this will make the cooldown time be expressed in seconds (cd_GattlingCooldown must be a float for this to work):
public float cd_GattlingCooldown = 0; public float cd_Gattling = 0.8f; // cooldown time in seconds
void Update () { //Handle the input commands HandleActionInput(); //Decrement the cooldown time if it's above 0.0 if (cd_GattlingCooldown > 0) cd_GattlingCooldown -= Time.deltaTime; }
void HandleActionInput() { if (Input.GetButton("Fire1")) { // fire only when cooldown time has elapsed if (cd_GattlingCooldown
void Fire()
{
cd_GattlingCooldown += cd_Gattling; // reload cooldown timer
GattlingRayCast();
}
HOW IT WORKS: Time.deltaTime is the time elapsed from last Update; if you subtract it from the cooldown timer, you're actually "consuming" the cooldown time each Update in a framerate independent speed.
Wow. I knew it could be implemented simply into the new code, but this was just about as easy as they come! thank Aldo!
Your answer
![](https://koobas.hobune.stream/wayback/20220613071706im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Questions about the fixed frame rate of Unity 1 Answer
How can I shooting script c#? 0 Answers
Time effected Bullets 0 Answers