我制作了一个小帆布游戏,但我无法让setInterval
在游戏循环中运作良好。
使用此代码,间隔运行一次,然后游戏循环似乎接管并一直运行。
<html>
<head>
<script type="text/javascript">
//Gameloop
function gameLoop(){
update();
draw();
requestAnimationFrame(gameLoop);
}
var x=50;
var y=50;
// update values
function update(){
x++;
//timer to increase speed once every 2 seconds
function timer(){
x = x +5;
}
var interval = setInterval(timer, 2000);
}
//Draw onto canvas
function draw(){
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
}
ctx.clearRect(0,0,800,800);
ctx.beginPath();
ctx.rect(x,y,25,25);
ctx.fill();
}
</script>
</head>
<body onload=gameLoop()>
<canvas id="canvas" width="800" height="800"></canvas>
</body>
</html>
答案 0 :(得分:1)
每个游戏圈都发射了另一个间隔。请尝试使用帧时间作为间隔。还可以将画布和上下文作为全局图获得,以增加每秒帧数。
var elFps = document.getElementById("fps");
var fps = 0;
var fpsInterval = setInterval(function(){
elFps.innerHTML = 'fps='+fps;
fps = 0;
}, 1000);
var speed = 1;
var gameStart = Date.now();
var speedUpTime = gameStart + 2000;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Gameloop
function gameLoop(){
var frameTime = Date.now();
if (frameTime >= speedUpTime) {
speed+=1;
speedUpTime += 2000;
}
fps++;
update();
draw();
requestAnimationFrame(gameLoop); // This is your looper
}
var x=50;
var y=50;
// update values
function update(){
x+=speed;
}
//Draw onto canvas
function draw(){
ctx.clearRect(0,0,800,800);
ctx.beginPath();
ctx.rect(x,y,25,25);
ctx.fill();
}
gameLoop();
&#13;
<div id="fps"> - </div>
<canvas id="canvas" width="800" height="800"></canvas>
&#13;