- Home /
Attack cooldown not correct?
I don't understand why attackTimer -= Time.deltaTime is not working. It only subtracts like .005 off the attack timer, and then i cannot attack again because the attack timer does not equal 2 anymore. Any help?
private Transform myTransform;
public int playerSpeed = 5;
public float attackTimer = 2.0f;
public GameObject projectile;
void Start ()
{
myTransform = transform; //Caching the transform variable
myTransform.position = new Vector3(0, 0, 0); //Spawning the player at a location
}
void Update ()
{
myTransform.Translate(Vector3.right * playerSpeed * Input.GetAxis("Horizontal") * Time.deltaTime); //Move player left and right
myTransform.Translate(Vector3.up * playerSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
if(myTransform.position.x > 4)
{
myTransform.position = new Vector3(4, myTransform.position.y, myTransform.position.z);
}
else if(myTransform.position.x < -4)
{
myTransform.position = new Vector3(-4, myTransform.position.y, myTransform.position.z);
}
if(myTransform.position.y > 5)
{
myTransform.position = new Vector3(myTransform.position.x, 5, myTransform.position.z);
}
else if(myTransform.position.y <=0)
{
myTransform.position = new Vector3(myTransform.position.x, 0, myTransform.position.z);
}
if(Input.GetKeyDown("space") && attackTimer == 2)
{
attackTimer -= Time.deltaTime;
Vector3 followPlayer = new Vector3(myTransform.position.x, myTransform.position.y, myTransform.position.z + 1.5f);
Instantiate(projectile, followPlayer, Quaternion.identity);
}
if(attackTimer <= 0)
{
attackTimer = 2;
}
Answer by Mmmpies · Jan 20, 2015 at 03:59 PM
You're checking if the timer == 2, it is for one frame then it no longer is. Check if the time is greater than 0 and that should fix it. Also shouldn't you just reduce the timer every frame rather than just when the keys being pressed?
The way I have it set up (or so I thought) is it will only attack if attackTimer is 2, then upon attacking the timer should subtract itself by Time.deltaTime until it reaches 0. When it reaches 0 it will set itself back to 2, allowing for another attack. Is that not what I am doing? $$anonymous$$aybe I misunderstand how the Time.deltaTime works?
O$$anonymous$$ your doing it the other way round. Sorry on my phone so can't see all the code in one go.
What id do for a cool down is check if the attackTimer less than or equal to 0 and attack key pressed then set the attackTimer to 2 and reduce every frame until 0 or less.
Answer by AngryBurritoCoder · Jan 20, 2015 at 04:01 PM
its because that line of code only runs for around 0.005 seconds, so it only subracts that, have a look at this, its used for weapon shooting for example, might work for you, its to do with fire rate, can be same as attack rate.
Your answer