所以我在HTML和Javascript的画布上创建了一个游戏。我想做出某种飞扬的鸟类游戏,但是当我按下一个键时,玩家的动画看起来确实很滑稽。请看:HTML5画布中的流畅动画
body {
overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Style.css"/>
</head>
<body onload="startgame()">
<canvas id="canvas"></canvas>
<script>
canvas.height=window.innerHeight;
canvas.width=window.innerWidth;
function startgame() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var x = 900;
var y = 300;
var w = 25;
var h = 500;
var yperson = 20;
var xperson = 200;
document.addEventListener("keydown", function() {
yperson -= 150;
});
function updateperson() {
yperson = yperson;
}
setInterval(createobject, 10);
function createobject() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x -= 1;
yperson += 0.5;
yperson *= 1.003;
ctx.fillStyle = "#009999";
ctx.fillRect(x,y,w,h);
ctx.fillStyle = "black";
ctx.fillRect(xperson,yperson,30,30);
if (x <= 50) {
if (yperson < 280 && xperson === x-30) {
x -= 1;
} else if (yperson > 280){
x += 1;
}
}
}
}
</script>
</body>
</html>
我希望它有一个流畅的动画了。我看到一些人说应该使用requestanimationframe来完成,但我不知道如何使用它。
在此先感谢。
看起来不错,但是'requestAnimationFrame'会稍微平滑,因为它更新显示。 –
我知道。 @SpencerWieczorek但是当你按下某个键时,这个人真的很快没有动画。 –
你只是直接将位置向上移动150像素。如果你想要动画你想向上施加一个力量,而不是直接向上翻译;在这种情况下,它们之间没有动画。 –