簡體   English   中英

html5畫布精靈表格隨機行/列

[英]html5 canvas sprite sheet random rows/columns

目前,代碼從Sprite表的一排圖像中進行選擇,並從屏幕的左至右顯示它,我想做的是像從中選擇隨機圖像一樣,但是從另一行中選擇圖像有3行,其中1行包含3個不同顏色的小行星32 x 32,第二行3具有不同的顏色64 x 64,最后3行具有不同的顏色128 x128。我如何隨機顯示各行以顯示不同的大小和顏色

這是當前代碼,任何幫助都將非常棒。

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

您可以使用一個對象來存儲所有小行星。 然后使用隨機數作為密鑰來獲取隨機小行星。

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'] );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM