efficient collision detection - tile based html5/javascript game
- by Tom Burman
Im building a basic rpg game and onto collisions/pickups etc now.
Its tile based and im using html5 and javascript.
i use a 2d array to create my tilemap.
Im currently using a switch statement for whatever key has been pressed to move the player, inside the switch statement.
I have if statements to stop the player going off the edge of the map and viewport and also if they player is about to land on a tile with tileID 3 then the player stops.
Here is the statement:
canvas.addEventListener('keydown', function(e) {
console.log(e);
var key = null;
switch (e.which) {
case 37:
// Left
if (playerX > 0) {
playerX--;
}
if(board[playerX][playerY] == 3){
playerX++;
}
break;
case 38:
// Up
if (playerY > 0) playerY--;
if(board[playerX][playerY] == 3){
playerY++;
}
break;
case 39:
// Right
if (playerX < worldWidth) {
playerX++;
}
if(board[playerX][playerY] == 3){
playerX--;
}
break;
case 40:
// Down
if (playerY < worldHeight) playerY++;
if(board[playerX][playerY] == 3){
playerY--;
}
break;
}
viewX = playerX - Math.floor(0.5 * viewWidth);
if (viewX < 0) viewX = 0;
if (viewX+viewWidth > worldWidth) viewX = worldWidth - viewWidth;
viewY = playerY - Math.floor(0.5 * viewHeight);
if (viewY < 0) viewY = 0;
if (viewY+viewHeight > worldHeight) viewY = worldHeight - viewHeight;
}, false);
My question is, is there a more efficient way of handling collisions, then loads of if statements for each key?
The reason i ask is because i plan on having many items that the player will need to be able to pickup or not walk through like walls cliffs etc.
Thanks for your time and help
Tom