简体   繁体   中英

HTML5 canvas sprite sheet random image

At the moment the code chooses one image from the sprite sheet and displays it across the sreen, what I'd like to do is select random images across the row and display them in the game, for example I want red/pink/green asteroids to display but at the moment its just displaying the green ones.

This is the current code, any help would be fantastic.

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

Add a variable to decide which image to use

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

When drawing use that variable to determine which image to use.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM