当前位置: 动力学知识库 > 问答 > 编程问答 >

html5 - How to make a character move smoothly in Javascript

问题描述:

I'm making a game, and I'd like to know how to make a character move more smoothly. The character can already move, but it moves really choppy; when you click the arrow key, it instantly appears 10 pixels ahead. I'd like it to move smoothly so it doesn't just "appear" 10 pixels ahead of itself.

Here is the Code:

document.onkeydown = checkKey;

var canvas;

var ctx;

var up;

var down;

var left;

var right;

var bobX = 200;

var bobY = 200;

var bobWidth = 30;

var bobHeight = 30;

window.onload = function() {

canvas = document.getElementById("gameCanvas");

ctx = canvas.getContext("2d");

var fps = 200; // frames per second

setInterval(function() {

updateAll();

drawAll();

}, 1000/fps)

};

var drawAll = function() {

// draw background

ctx.fillStyle = "white";

ctx.fillRect(0, 0, canvas.width, canvas.height);

// draw bob

ctx.fillStyle = "red";

ctx.fillRect(bobX, bobY, bobWidth, bobHeight);

};

var updateAll = function() {

if (up == true) {

up = false;

}

if (down == true) {

bobY += 1;

down = false;

}

if (left == true) {

bobX -= 1;

left = false;

}

if (right == true) {

bobX += 1;

right = false;

}

};

function checkKey(e) {

e = e || window.event;

if (e.keyCode == '38') {

up = true;

}

else if (e.keyCode == '40') {

down = true;

}

else if (e.keyCode == '37') {

left = true;

}

else if (e.keyCode == '39') {

right = true;

}

}

I tried doing moving it by one pixel every keypress, but it moves very slowly when I do that.

网友答案:

Your screen has maximum refreshrate, usually 60 fps. Some screens can get up to 120fps, but that's a rather rare case.

So what is happening here:

var fps = 200; // frames per second
setInterval(function() {
    updateAll();
    drawAll();
    }, 1000/fps)

};

The canvas gets redrawn and the position gets updated at a rate which your screen can't catch up with. You simply can't see that your character only moves 1 pixel instead of 10 pixel.

Solution would be to use requestAnimationFrame instead. Which invokes when the screen refreshes:

function animate() {
    requestAnimationFrame(animate);
    updateAll();
    drawAll();
};
animate();
分享给朋友:
您可能感兴趣的文章:
随机阅读: