0

現時点では、コードはスプライト シートから画像の 1 つの行から選択し、画面の左から右に表示します。 32×32の3つの異なる色の小惑星の1つの行、2行目の3つの異なる色の64×64、および最後の行の3つの異なる色の128×128の3つの行があります。行をランダムにして、異なるサイズと色を表示するにはどうすればよいですか

これは現在のコードです。どんな助けも素晴らしいでしょう。

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 に答える