繁体   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