Javascript 使用requestAnimationFrame制作游戏动画
我试图用requestAnimFrame制作一些简单的游戏,但动画不起作用,我也不知道为什么。也许有人能帮忙?代码如下:Javascript 使用requestAnimationFrame制作游戏动画,javascript,animation,canvas,game-engine,requestanimationframe,Javascript,Animation,Canvas,Game Engine,Requestanimationframe,我试图用requestAnimFrame制作一些简单的游戏,但动画不起作用,我也不知道为什么。也许有人能帮忙?代码如下: // requestAnimationFrame() shim by Paul Irish // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ window.requestAnimFrame = (function(){ return window.requestAnimat
// requestAnimationFrame() shim by Paul Irish
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
//Create canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);
// The main game loop
var lastTime;
function main() {
var now = Date.now();
var dt = now - lastTime;
draw();
update(dt);
lastTime = now;
requestAnimFrame(main);
}
main();
function ball(){
this.radius = 5;
this.x = 300;
this.y = 50;
this.vx = 200;
this.vy = 200;
this.ax = 0;
this.ay = 0;
this.color = "red";
this.draw = function(){
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc( this.x, this.y, this.radius, 0, 2 * Math.PI );
ctx.fill();
};
}
function draw() {
newBall = new ball();
newBall.draw();
}
function update(dt) {
newBall = new ball();
newBall.x += newBall.vx * dt;
}
在
更新(dt)
功能球不移动,我不知道为什么…您的代码中有几个错误:
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
theBall.draw();
}
还有其他几件事,但现在应该这样做。一件事是
dt
几乎总是一样的。另一件事是每次都要创建一个新的球。这是你的意图,还是你只是想移动那个?