【问题标题】:HTML5 canvas sprite sheet random imageHTML5 画布精灵表随机图像
【发布时间】:2013-02-13 11:45:42
【问题描述】:

目前代码从精灵表中选择一个图像并将其显示在屏幕上,我想做的是在行中选择随机图像并在游戏中显示它们,例如我想要红色/粉红色/green 小行星要显示,但目前它只显示绿色小行星。

这是当前代码,任何帮助都会很棒。

function Enemy() {
    this.srcX = 0;
    this.srcY = 0;
    this.width = 64;
    this.height = 64;
    this.previousSpeed = 0;
    this.speed = 2;
    this.acceleration = 0.005;
    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.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
    this.checkEscaped();
};

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


    【解决方案1】:

    添加一个变量来决定使用哪个图像

    function Enemy() {
    ...
    this.imageNumber = Math.floor(Math.random()*3);
    ...
    }

    绘制时使用该变量来确定要使用的图像。

    Enemy.prototype.draw = function () {
    ...
    ctxEnemy.drawImage(imgSprite,this.srcX+this.imageNumber* this.width,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
    ...
    }

    【讨论】:

    • 您先生是个天才!我还有一个问题,我有 3 行,其中 1 行小行星 32 x 32,第 2 行 64 x 64,最后一行 128 x 128。我如何也随机 y 轴?
    • @Nick 你应该发布一个新问题(包括代码示例,就像你之前做的那样)。
    猜你喜欢
    • 2013-02-13
    • 2013-07-28
    • 2014-04-28
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    相关资源
    最近更新 更多