2017-08-07 64 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循環之後在渲染函數中加入這個。