2016-05-05 110 views
0

我正在研究應該讓10個球不同的顏色並從牆上反彈的代碼,但是當我運行代碼時它會一直得到一個或兩個不同的彩色球,或者它會每隔1/10次完美工作。任何想法爲什麼? 帆布動畫 我每次運行此代碼時都有不同的結果,怎麼回事?

<body> 
<canvas id = "canvas" width="600" height = "500"> </canvas> 

<script> 

var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 
var width = 300 //changes canvas size 
var height = 400 
width = canvas.width 
height = canvas.height 
    /* In this constructor, the starting position 
    of the ball is set to this.x and this.y 
    */ 
var Ball = function() { 
    this.x = Math.random() * canvas.width; 
    this.y = Math.random() * canvas.height; 
    this.xSpeed = -2; // -2 means 2 pixels left for every step of animation. 
    this.ySpeed = 3; 
    var circle = function (x, y, radius, color, fill) { //function to make drawing circles faster 
      ctx.strokeStyle = color 
      ctx.beginPath(); 
      ctx.arc(x, y, radius, 0, Math.PI * 2, false); 
      if (fill === true) { 
       ctx.fillStyle = color; 
       ctx.fill() 
      } 
      ctx.stroke(); 
     } 
     // The Ball maker 
    x = Math.floor(Math.random() * 10) 
    myColors = ["Green", "Red", "Orange", "Yellow", "Chocolate", "Brown", "Silver", "Black", "Purple", "Blue"] 
    Ball.prototype.draw = function() { 
     circle(this.x, this.y, 3, myColors[x], true) 
    }; 
    // this will move the balls 

    Ball.prototype.move = function() { 
     this.x += this.xSpeed; 
     this.y += this.ySpeed; 
    }; 

    Ball.prototype.checkCollision = function() { //makes the balls bounce off walls 
     if (this.x < 0 || this.x > width) { 
      this.xSpeed = -this.xSpeed; 
     } 
     if (this.y < 0 || this.y > height) { 
      this.ySpeed = -this.ySpeed; 
     } 
    } 
} 
var moBalls = [] //stores balls to be called later 
for (var x = 0; x < 10; x++) { 
    moBalls[x] = new Ball() 
} 
width = canvas.width 
height = canvas.height 
setInterval(function() { 
    ctx.clearRect(0, 0, width, height); 
    for (x = 0; x < 10; x++) { //takes the balls from moBalls and moves the ten of them 
     moBalls[x].draw() 
     moBalls[x].move() 
     moBalls[x].checkCollision(); 
    } 
    ctx.lineWidth = 4 
    ctx.strokeRect(0, 0, width, height); //makes the walls 
}, 30); 

</script> 

</body> 
</html> 
+0

沒有得到你所期望的和你得到的。你能給個例子嗎? –

+2

在可能存在的其他問題中,您需要在使用它的所有函數中聲明變量'x'。你使用它就好像它是一個局部變量,但它是全局的。另外,在構造函數中設置構造函數原型*幾乎肯定不是正確的做法。 – Pointy

回答

0

我敢肯定那是因爲你使用在多個地方可變x不使用var使用關鍵字(如@pointy說,你是不是它聲明) 。

使用var x您可以在其中生成從數組中選擇顏色的隨機數,也可以在for循環中調用draw方法。

甚至更​​好,使用不同的變量名稱,將清楚變量的意圖是什麼。例如:

var randomColorIndex = Math.floor(Math.random() * 10) 
var myColors = ["Green", "...", "Blue"] 
Ball.prototype.draw = function() { 
    circle(this.x, this.y, 3, myColors[randomColorIndex], true) 
}; 

(我知道這似乎有點長,但它僅僅是一個例子;使用任何手段,對你最重要)。

相關問題