2013-03-05 46 views
1

我想隨機選擇一個語句,其中的值從裏面的精靈表中的某個點繪製。這是我現有的代碼。Javascript的html5帆布隨機開關語句

this.asteroid = Math.floor(Math.random()*4); 
switch(this.asteroid) 
    { 
    case 1: 
     this.srcX = 0; 
     this.srcY = 528; 
     this.width = 32; 
     this.height = 33; 
     break; 
    case 2: 
     this.srcX = 32; 
     this.srcY = 528; 
     this.width = 32; 
     this.height = 33; 
     break; 
    case 3: 
     this.srcX = 64; 
     this.srcY = 528; 
     this.width = 32; 
     this.height = 33; 
     break; 
    case 4: 
     this.srcX = 0; 
     this.srcY = 565; 
     this.width = 62; 
     this.height = 60; 
     break; 
    } 

我稍後繪製它選擇的值。

問題我有它的唯一繪製紫色/灰色小行星,目前情況2和3.我已經在主屏幕上設置了一種字體,告訴我哪種情況下它先繪製並刷新,直到它說1或4它仍然吸引2和3

+0

一個問題是,Math.floor(的Math.random()* 4)將產生0-3的數字。如果你想讓它產生1-4的數字,在* 4) – Keeleon 2013-03-05 15:40:20

+0

'Math.floor(Math.random()* 4)之後加+1;'可以返回0,1,2,3而不是4。你不明白爲什麼你看不到它返回1的情況。 – tafa 2013-03-05 15:40:37

回答

0
this.asteroid = Math.floor(Math.random()*4); 

應該 this.asteroid = Math.floor(Math.random()*5)+1; //所以你可以指望的case 4,並在控制檯中 「跳」 過case 0

參見: http://jsbin.com/ulirom/3/

2

您的代碼的方式是,它當前會生成數字0,1,2和3.因此,您應該會看到case 1:出現過一些時間,但從未出現過case 4:。要解決這個問題,只需調整你的個案。

個人而言,如下我想改寫這個代碼:

var srcX = [0,32,64,0], 
    srcY = [528,528,32,565], 
    width = [32,32,32,62], 
    height = [33,33,33,60], 
    rand = Math.floor(Math.random()*4); 
this.srcX = srcX[rand]; 
this.srcY = srcY[rand]; 
this.width = width[rand]; 
this.height = height[rand]; 
+0

問題在於,當某些值彼此屬於某個值時,它將隨機選擇x和y – Nick 2013-03-07 15:58:27