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();
因爲每次循環渲染時,都會再次從頭創建所有球。嘗試移動'球[我] =新球();'*外渲染'* –
你期待發生什麼 - 球反彈?你沒有事件循環,每5秒鐘超時。你需要每秒處理幾次(30次左右= 30fps)。作爲一個例子來看看http://www.playmycode.com/blog/2011/08/building-a-game-mainloop-in-javascript/ –