Search code examples
javascriptcsscollision

Game Not Detecting Collision Between Character and border


All my collision is working accept when the character collides with the border. I want the character to re-spawn so when the character collides with the border I would use his code:

 left = 10;
 var reLeft = {'left':left + "px"};
 $('#char').css(reLeft);
 top = 10;
 var reTop = {'top':top + "px"};
 $('#char').css(reTop);

But it does not do anything when the character collides with it.


Solution

  • In your checkCollision function you should add a check if the player is off screen.

    Adding this to the end of the function will give you a basic idea what I'm referring to.

         if($('#char').offset().top < 0 || $('#char').offset().top > window.innerHeight || $('#char').offset().left < 0 || $('#char').offset().left > window.innerWidth ){
          console.log('Off Screen');
         }
    

    I would suggest making this into a function where you can detect if anything is off screen.

    The Example I gave does not take into account offsets. I'm trying to keep it as simple as possible.