2013-02-27 124 views
0

目前代碼從精靈表中的一行圖像中選擇並顯示它從屏幕的左側到右側,我想要做的是選擇隨機圖像它做但從一個不同的行,例如我有3行1行3個不同的彩色小行星32乘32,第2行3不同顏色64乘64和最終行3不同顏色128乘128.我怎麼會隨機行以顯示不同的尺寸以及顏色html5 canvas精靈表隨機行/列

這是當前的代碼,任何幫助將是太棒了。

function Enemy() { 
this.srcX = 0; 
this.srcY = 528; 
this.width = 32; 
this.height = 33; 
this.previousSpeed = 0; 
this.speed = 2; 
this.acceleration = 0.005; 
this.imageNumber = Math.floor(Math.random()*3); 
this.drawX = Math.floor(Math.random() * 1000) + gameWidth; 
this.drawY = Math.floor(Math.random() * gameHeight); 
this.collisionPointX = this.drawX + this.width; 
this.collisionPointY = this.drawY + this.height;  
} 

Enemy.prototype.draw = function() { 
this.drawX -= this.speed; 
ctxEnemy.drawImage(imgSprite,this.srcX+this.imageNumber*this.width,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height); 
this.checkEscaped(); 
}; 

Enemy.prototype.assignValues = function() { 

} 

Enemy.prototype.checkEscaped = function() { 
if (this.drawX + this.width <= 0) { 
    this.recycleEnemy(); 
} 
}; 

Enemy.prototype.recycleEnemy = function() { 
this.drawX = Math.floor(Math.random() * 1000) + gameWidth; 
this.drawY = Math.floor(Math.random() * gameHeight); 
}; 

function clearCtxEnemy() { 
ctxEnemy.clearRect(0, 0, gameWidth, gameHeight); 
} 

回答

0

您可以使用一個對象來存儲所有的小行星。然後用一個隨機數作爲一個關鍵來得到一個隨機小行星。

var min = 1; 
var max = 9; 
var key = Math.floor(Math.random() * max) + min; 

var asteroids = { 
    1 :{ 
     'width' : 64, 
     'height' : 64, 
     'colour' : 'blue' 
    }, 
    2 : { 
     'width' : 64, 
     'height' : 64, 
     'colour' : 'red' 
    }, 

    //repeat until the last one.... 

    9 : { 
     'width' : 128, 
     'height' : 128, 
     'colour' : 'green' 
    } 
}; 


console.log(asteroids[key]['colour']); 
console.log(asteroids[key]['width']); 
console.log(asteroids[key]['height']); 
+0

我會將這個包含在同一個js文件中嗎? – Nick 2013-03-05 14:01:23

+0

是的,這將工作。 – Jrod 2013-03-05 14:09:00

+0

我需要在文件中添加其他內容嗎? – Nick 2013-03-05 14:31:23