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?