0

我尝试使用 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;
}

update(dt)功能球不移动,我不知道为什么......

4

1 回答 1

0

您的代码中有几个错误:

  1. 您在函数之外初始化变量,为此始终使用初始化程序(立即调用的函数)。
  2. 正如 kalley 所提到的,您在每次抽签的起始位置创建一个新球,而不是使用全局对象。
  3. 即使您的球可以正确绘制,它也会在下一帧内的绘图区域之外,因为 Date.now() 以秒为单位(使用 .getMilliseconds())。
  4. 最后,球保持在同一位置,因为每次绘制后都没有清理画布。

你在找什么:

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

还有其他几件事,但这个小提琴现在应该做。

于 2013-07-13T07:44:48.527 回答