Is this the optimal method to check for collisions in a 2d-based game?  I put together a working demo of 2D collisions here (WSAD to move, orange blocks collide).I currently use the following code to check for collisions:function checkmove(x, y) {  if(level[Math.floor(x/20)][Math.floor(y/20)] == 1 || level[Math.ceil(x/20)][Math.floor(y/20)] == 1 || level[Math.floor(x/20)][Math.ceil(y/20)] == 1 || level[Math.ceil(x/20)][Math.ceil(y/20)] == 1) {    return false;  } else {    return true;  }}Update function:function update(key) {  switch(key) {    case W:      if(checkmove(pos.x, pos.y-2)) {        pos.y -= 2;        break;      } else {        break;      }     case S:      if(checkmove(pos.x, pos.y+2)) {      pos.y += 2;        break;      } else {        break;      }    case A:      if(checkmove(pos.x-2, pos.y)) {      pos.x -= 2;      break;      } else {        break;      }    case D:      if(checkmove(pos.x+2, pos.y)) {      pos.x += 2;       break;      } else {        break;      }    default:      break;  }}This is called before movement is applied the the 'player'.  The game is laid out as a 2D array of 1's and 0's for testing purposes.Can I use fewer mathematical operations (less expensive for each tick) to check for a collision between the player and a '1' on my game grid?
2D tilemap collision method
javascript;game;collision
Those refactoring will help :  idea is to test only upper-left point and bottom-right point, which should be ok 99.99999% of the time.(Rq : i know we could test wether the second test is in fact about the same tile, but i guess that would be slower).function checkmove(x, y, w, h) {  var tileX, tileY, thisTile;  tileX = Math.floor(x/20) ;  tileY = Math.floor(y/20) ;  thisTile = level[tileX][tileY];   if(thisTile == 1 ) return false;  tileX = Math.floor((x+w)/20) ;  tileY = Math.floor((y+h)/20) ;   thisTile = level[tileX][tileY];  if(thisTile == 1 ) return false;  return true;}For your move section, there's a big issue : it is not time based. So it will run at different speed on different devices. Not good.  Define a basic game loop where you measure time. If you're interested, you can watch this fiddle i made : http://jsfiddle.net/KVDsc/ And have your game objects move by delta x = delta time * speed.function update(key, dt) {  var dx, dy, newX, newY;  dx   = this.speedX * dt;  dy   = this.speedY * dt;  newX = pos.x;  newY = pos.y;  var kpc = 0 ;                          // key pressed count;  if      (key == W && ++kpc) newY-=dy;   else if (key == S && ++kpc) newY+=dt;   if      (key == A && ++kpc) newX-=dx;   else if (key == D && ++kpc) newX+=dx;   if( kpc && checkmove(newX, newY) ) {     pos.x = newX;      pos.y = newY;   }}All this should be faster. Notice that you might want to use if instead of select to enable going, say, both to the right and downward.