I am attempting to develop a game with canvas element. Right now, I am drawing tiles (colored s开发者_StackOverflow中文版quares) as the background, and the hero controlled by arrow keys based off of this demo: http://www.lostdecadegames.com/demos/simple_canvas_game/
However, calling showDungeon() to draw my background makes the movement of the hero not smooth like in the demo. I think the problem is that I am drawing each tile as 32x32, which is making the movement slow in Chrome. Any suggestions or code optimizations I can do? The movement is fine when the tiles are 16x16, but I want the tiles 32x32. I kind of dont want to use CSS to double the size of the canvas as that can ruin the graphics with anti-aliasing. http://www.html5rocks.com/en/tutorials/casestudies/onslaught.html#toc-pixelated
// Draw everything
var render = function() {
showDungeon();
ctx.drawImage(img, hero.x, hero.y);
};
// The main game loop
var main = function() {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
};
// Let's play this game!
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
unrelated problem: for some reason, I couldnt draw a green square as a hero in render(), so i used an image instead. http://jsfiddle.net/4M5Xz/4/
You have a strange loop in the code:
function showDungeon() {
for (var x = 0; x < (15*32); x++) {
for (var y = 0; y < (15*32); y++) {
...
}
}
}
It's like you are drawing the background too many times. I changed it to:
function showDungeon() {
for (var x = 0; x < 15; x++) {
for (var y = 0; y < 15; y++) {
...
}
}
}
and it was smooth again.
精彩评论