In my top down game I can move the character around and the character will even face the direction he is moving.
However, there is some weird behavior I'm having: when you hold down one direction and then another direction the graphic updates to that direction, but if you keep holding the direction prior it does not update to the correct graphic.
Here is my function that handles the rendering of the player graphic. When that happens it looks like the character is walking sideways. I haven't added animation yet. It just tries to have the right graphic with the corresponding direction.
render: function() {
var game = roguelike.game;
var map = roguelike.map;
var image = game.library.images[1];
var ctx = game.library.ctx;
var centerX = game.library.canvas.width / 2 - map.tileSize / 2;
var centerY = game.library.canvas.height / 2 - map.tileSize / 2;
switch(this.facing) {
case "left":
var cropX = 1 * map.tileSize;
var cropY = 5 * map.tileSize;
break;
case "up":
var cropX = 1 * map.tileSize;
var cropY = 7 * map.tileSize;
break;
case "right":
var cropX = 1 * map.tileSize;
var cropY = 6 * map.tileSize;
break;
case "down":
var cropX = 1 * map.tileSize;
var cropY = 4 * map.tileSize;
break;
}
ctx.drawImage(
image,
cropX,
cropY,
map.tileSize,
map.tileSize,
centerX,
centerY,
map.tileSize,
map.tileSize
);
}
Also you might want to see how I handle my player.facing
state. I do it this way.
window.onkeydown = function (event) {
var player = roguelike.player;
switch (event.keyCode) {
//Left
case 37:
player.facing = "left";
player.moving.left = true;
break;
//Up
case 38:
player.facing = "up";
player.moving.up = true;
break;
//Right
case 39:
player.facing = "right";
player.moving.right = true;
break;
//Down
case 40:
player.facing = "down";
player.moving.down = true;
break;
}
};