HTML5画布精灵表随机图像

时间:2013-02-27 15:34:14

标签: javascript html5 canvas

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

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

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

1 个答案:

答案 0 :(得分:0)

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

  

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

相关问题