I'm building a basic RPG game and I'm looking at collisions/pickups etc now.
It's tile based and I'm using HTML5 and Javascript.
I use a 2D array to create my tilemap.
I'm currently using a switch statement for whatever key has been pressed to move the player.
I have if statements to stop the player going off the edge of the map and viewport. If the 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);
Is there a more efficient way of handling collisions, than 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.