2013-02-27 148 views
0

目前代碼從精靈表中選擇一個圖像並將其顯示在屏幕上,我想要做的是在整行上選擇隨機圖像並將其顯示在遊戲中例如我想要顯示紅色/粉紅色/綠色小行星,但目前它只顯示綠色小行星。HTML5 canvas精靈表隨機圖像

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

function Enemy() { 
    this.srcX = 0; 
    this.srcY = 0; 
    this.width = 64; 
    this.height = 64; 
    this.previousSpeed = 0; 
    this.speed = 2; 
    this.acceleration = 0.005; 
    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.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height); 
    this.checkEscaped(); 
}; 

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

添加一個變量來決定使用哪個圖像

function Enemy() {
...
this.imageNumber = Math.floor(Math.random()*3);
...
}

當繪製使用該變量以確定要使用哪個圖像。

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

+0

你的先生是個天才! 我還有一個問題,我有3行1行32乘32小行,第2行64乘64和最後128行128行。我怎麼也隨機y軸? – Nick 2013-02-27 16:19:56

+0

@Nick你應該發佈一個新的問題(完整的代碼示例,就像你之前做的一樣)。 – derekv 2013-02-27 18:48:53