0

I am using some collision code I found on stack overflow, it uses .setInterval which when lowered to something like in a game doesn't seem very efficient. I wish to reset #div1 upon a false result.

Would an EventListener be preferable? What would be the best alternative for something with collisions possibly happening every second?

window.setInterval(function() {
  var bang = collision(collisionOne, collisionTwo);
  $('#result').text(bang);
   if (bang) === false){
     $('#div1').detach();
     }
  }, 20);
Bonstark
  • 45
  • 8
  • 1
    Generally you should have a game loop for all the logics. Put the collision check in there and get rid of `.setInterval`. – Derek 朕會功夫 Nov 16 '17 at 07:22
  • 1
    How are you detecting a collision? – Chris Phillips Nov 16 '17 at 07:22
  • 1
    Possible duplicate of [Is setInterval CPU intensive?](https://stackoverflow.com/questions/6650134/is-setinterval-cpu-intensive) – E. Villiger Nov 16 '17 at 07:23
  • Derek, the game is really small but that's something I should definitely plan for, or just start again with that in mind. Chris Phillips, I'm using [This](http://jsfiddle.net/nGRwt/7/) jsfiddle's collision code. E. Villiger, I have read that thread, but don't think it's not really applicable. – Bonstark Nov 16 '17 at 07:33

1 Answers1

1

In some cases, the function might need longer than the interval time to finish execution. Consider using setInterval in every 5 seconds, variables might prevent the request from completing on time. What would happen is that you'll end up with a bunch of queued requests that may not necessarily return in order. You can use instead...

function interval(){

    setTimeout(interval, wait);
};

where the wait is a time variable.

A.D.
  • 2,352
  • 2
  • 15
  • 25
  • addy, thanks for your input. I think I am using the wrong tool for the job. The code I am using is from [this](http://jsfiddle.net/nGRwt/7/) fiddle. – Bonstark Nov 16 '17 at 07:37
  • what you wana do here ? – A.D. Nov 16 '17 at 07:40
  • I am using 3 collision detections for 3 different events, and setting a very short interval. First is resetting a moving object (div) upon contact with the containing div, secondly detecting the moving object hitting an already moving object (bullet->enemy entity) thirdly the enemy entity hitting the player(that doesn't move). It doesn't seem like I'm using it correctly and want to know what would be the best methodology would be. – Bonstark Nov 16 '17 at 07:44
  • So there you can use drag,start,stop event of drag in jquery try once... – A.D. Nov 16 '17 at 07:47