【问题标题】:html5 canvas sprite sheet random rows/columnshtml5画布精灵表随机行/列
【发布时间】:2013-02-13 19:36:15
【问题描述】:

目前代码从精灵表中的一行图像中选择并从屏幕的左到右显示它,我想做的是选择随机图像,就像它所做的那样,但从不同的行中,例如,我有 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);
}

【问题讨论】:

    标签: javascript html canvas sprite-sheet


    【解决方案1】:

    您可以使用一个物体来存储您所有的小行星。然后用一个随机数作为key,得到一个随机小行星。

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

    【讨论】:

    • 我会在同一个js文件中包含这个吗?
    • 我还需要在文件中添加什么吗?
    • 很可能,是的。这只是如何组织所有小行星以便您可以访问随机小行星的一个示例。
    • 可能,最好的方法就是尝试一下。
    猜你喜欢
    • 2013-02-13
    • 2013-07-28
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2017-08-26
    • 2018-07-24
    相关资源
    最近更新 更多