html5画布精灵表随机行/列

时间:2013-02-27 20:16:24

标签: javascript html canvas sprite-sheet

当代码从精灵表中的一行图像中选择并显示它从屏幕的左侧到右侧时,我想要做的是选择随机图像,就像它在做,但从另一行,例如我有3行,1行3个不同颜色的小行星32乘32,第2行3不同颜色64乘64,最后行3不同颜色128乘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);
}

1 个答案:

答案 0 :(得分: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'] );