Adding delay between damage

I have a bunch of enemies chasing my main-character, and if they intersect I want them to damage him and that’s all good. The problem is that right now they damage him as long as they stand around him, every frame! and since it gets called every frame my character’s HP reaches 0 almost instantly.

I’ve tried adding delay and I’ve tried a timertask, but can’t get it to work.

This is the code I use to check for intersection:

private void checkCollision(Canvas canvas) {
    synchronized (getHolder()) {
        Rect h1 = happy.getBounds();
        for (int i = 0; i < enemies.size(); i++) {
            for (int j = 0; j < bullets.size(); j++) {
                Rect b1 = bullets.get(j).getBounds();
                Rect e1 = enemies.get(i).getBounds();
                if (b1.intersect(e1)) {
                // this is the statement that needs some sort of delay, I want them to damage him every 2 seconds they intersect him.

                if(enemies.get(i).getHP() <= 0){
                    enemies.get(i).death(canvas, enemies);
                if(happy.getHP() <= 0){

If anyone knows the logic to do this please do tell.


Just add a cooldown for any action that needs to be delayed. When the action is performed set the cooldown to a proper value and deduct the time in your update loop. Something like:

Class Entity 
  const float COOLDOWN_TIME = 10; //in seconds

  private float cooldown = 0;


public void Update(float time)
  cooldown -= time;

public bool attack()
  if(cooldown <= 0)
    cooldown = COOLDOWN_TIME; 
    return true;
    return false;



Source : Link , Question Author : Green_qaue , Answer Author : Mikael Högström

Leave a Comment