0

目前代码从精灵表中的一行图像中选择并从屏幕的左到右显示它,我想做的是选择随机图像,就像它所做的一样,但是从不同的行中选择,例如我有 3 行,其中 1 行 3 个不同颜色的小行星 32 x 32,第 2 行 3 个不同颜色的 64 x 64,最后一行 3 个不同颜色的 128 x 128。我将如何随机显示不同的大小和颜色

这是当前代码,任何帮助都会很棒。

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);
}
4

1 回答 1

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'] );
于 2013-02-27T20:53:26.073 回答