0

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

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

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

1 回答 1

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

于 2013-02-27T15:56:16.570 回答