2017-08-07 67 views
0

动画球试图以动画球,与在画布上的间隔不能在画布上

做球出现在每个N *秒出现,但我不能让他们动:C

我“M做错了

https://jsbin.com/mexofuz/26/edit?js,output

function Ball(){ 
    this.X = 50; 
    this.Y = 50; 
    this.radius = Math.floor(Math.random()*(30-10)+10); 
    this.color = getRandomColor(); 
    this.dx = Math.floor(Math.random()*(20-10)+10); 
    this.dy = Math.floor(Math.random()*(20-10)+10); 
} 
Ball.prototype.draw = function(){ 
    context.fillStyle = this.color; 
    context.beginPath(); 
    context.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true); 
    context.closePath(); 
    context.fill(); 
} 
Ball.prototype.animate = function(){ 
    if(this.X<0 || this.X>(w-this.radius)) this.dx=-this.dx; 
    if(this.Y<0 || this.Y>(h-this.radius)) this.dy=-this.dy; 
    this.X+=this.dx; 
    this.Y+=this.dy; 
} 

var balls = []; 

function render() { 
    context.fillStyle = "white"; 
    context.fillRect(0, 0, w, h); 
    for(var i = 1;i<=20;i++){ 
     balls[i] = new Ball(); 
     setTimeout(Ball.prototype.draw.bind(this.balls[i]), 5000 * i); 
    // Ball.prototype.animate.bind(this.balls[i]); 
     if (balls[i].X < 0 || balls[i].X > w-balls[i].radius) { 
     balls[i].dx = -balls[i].dx; 
     } 

     if (balls[i].Y < 0 || balls[i].Y > h-balls[i].radius) { 
     balls[i].dy = -balls[i].dy; 
     } 
     balls[i].x += balls[i].dx 
     balls[i].y += balls[i].dy 
} 
    console.log(balls); 
} 
render(); 
+0

因为每次循环渲染时,都会再次从头创建所有球。尝试移动'球[我] =新球();'*外渲染'* –

+0

你期待发生什么 - 球反弹?你没有事件循环,每5秒钟超时。你需要每秒处理几次(30次左右= 30fps)。作为一个例子来看看http://www.playmycode.com/blog/2011/08/building-a-game-mainloop-in-javascript/ –

回答

0

你需要做两件事情 - 首先,更新你的 '球' 的位置。目前你只需要做一次,你需要将它放在setInterval中,或者每秒更新一次。其次,每当球移动时(每更新一次就好,而不是每球一次),您需要重新绘制画布。举个例子:

setInterval(function() { 
balls.forEach(a=>a.animate()); 
context.fillStyle = "white"; 
context.fillRect(0, 0, w, h); 
balls.forEach(a=>a.draw()); 
}, 30); 

在for循环之后在渲染函数中加入这个。