[英]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: 您的代码中有几个错误:
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.