简体   繁体   English

使用requestAnimationFrame制作动画游戏

[英]Animating game using requestAnimationFrame

I tried to make some simply game using requestAnimFrame but animation doesn't work and I don't know why. 我试图使用requestAnimFrame做一些简单的游戏,但是动画不起作用,我也不知道为什么。 Maybe some one can help? 也许有人可以帮忙吗? Here is the code: 这是代码:

// 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;
}

In update(dt) function ball dosen't move and I don't know why... update(dt)函数中,球不动,我也不知道为什么...

There are several errors in your code: 您的代码中有几个错误:

  1. You're initializing variables outside of a function, always use an initializer (immediately invoked function) for that. 您正在初始化函数外部的变量,请始终为此使用初始化程序(立即调用的函数)。
  2. As mentioned by kalley you are creating a new ball at the starting position for every draw instead of using a global object. 如kalley所述,您将在每次平局的起始位置创建一个新球,而不是使用全局对象。
  3. Even if your ball would draw correctly it would be outside the drawing area within the next frame because Date.now() is measured in seconds (use .getMilliseconds()). 即使您的球正确绘制,它也会在下一帧的绘制区域之外,因为Date.now()的单位是秒(使用.getMilliseconds())。
  4. Lastly the ball stays at the same position because the canvas isn't cleaned up after each draw. 最后,球保持在同一位置,因为每次平局后都不会清理画布。

what you're looking for: 您要寻找的是:

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

There are several other things but this fiddle should do for now. 还有其他几件事情,但是这个小提琴现在应该做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM