Javascript 使用requestAnimationFrame制作游戏动画

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

我试图用requestAnimFrame制作一些简单的游戏,但动画不起作用,我也不知道为什么。也许有人能帮忙?代码如下:

// 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)
功能球不移动,我不知道为什么…

您的代码中有几个错误:

  • 在函数外部初始化变量时,始终使用初始值设定项(立即调用的函数)
  • 正如kalley所提到的,您在每次平局的起始位置创建一个新球,而不是使用全局对象
  • 即使你的球画得正确,它也会在下一帧内超出绘图区域,因为Date.now()是以秒为单位测量的(使用.getmillizes()
  • 最后,球保持在相同的位置,因为每次平局后画布都没有清理干净
  • 你在寻找什么:

    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        theBall.draw();
    }
    

    还有其他几件事,但现在应该这样做。

    一件事是
    dt
    几乎总是一样的。另一件事是每次都要创建一个新的
    球。这是你的意图,还是你只是想移动那个?