1

我正在尝试随机选择其中包含值的语句,该语句从精灵表中的某个点绘制。这是我拥有的当前代码。

    this.asteroid = Math.floor(Math.random()*7+1);
    switch(this.asteroid)
    {
    case 0:
        this.srcX = 0;
        this.srcY = 528;
        this.width = 32;
        this.height = 33;
        break;
    case 1:
        this.srcX = 32;
        this.srcY = 528;
        this.width = 32;
        this.height = 33;
        break;  
    case 2:
        this.srcX = 64;
        this.srcY = 528;
        this.width = 32;
        this.height = 33;
        break;
    case 3:
        this.srcX = 63;
        this.srcY = 565;
        this.width = 62;
        this.height = 60;           
        break;
    case 4:
        this.srcX = 125;
        this.srcY = 565;
        this.width = 62;
        this.height = 60;           
        break;
    case 5:
        this.srcX = 187;
        this.srcY = 565;
        this.width = 62;
        this.height = 60;           
        break;
    case 6:
        this.srcX = 0;
        this.srcY = 632;
        this.width = 116;
        this.height = 120;          
        break;  
    }

然后我稍后会绘制它选择的值。

我的问题主要是绘制所有这些,但同时只绘制一个空白图像,我检查了所有 X 和 Y 位置,它们都是正确的并且在精灵表中匹配。

下面是我用来绘制精灵的代码:

this.drawX -= this.speed;
ctxEnemy.drawImage(imgSprite,
    this.srcX+this.width,this.srcY,this.width,this.he‌​ight,
    this.drawX,this.drawY,this.width,this.height);
this.checkEscaped();
4

2 回答 2

2

Math.floor(Math.random()*7+1)可以取 1 到 7 之间的值。删除+1.

于 2013-03-07T16:03:30.833 回答
0

我认为您的绘图代码可能有问题:

this.drawX -= this.speed;
ctxEnemy.drawImage(imgSprite,
    this.srcX+this.width,this.srcY,this.width,this.he‌​ight,
    this.drawX,this.drawY,this.width,this.height);
this.checkEscaped();

在行中:this.srcX+this.width,this.srcY,this.width,this.he‌​ight, 您正在将对象宽度添加到源位置。我认为这可能会影响您的精灵图。请参阅下面的参考评论示例:

// draw image to screen drawImage(imageObject, 
//     sourceX, sourceY, sourceWidth, sourceHeight,
//     destinationX, destinationY, destinationWidth, destinationHeight)
ctx.drawImage(imageObject, 
    this.srcX, this.srcY, this.width, this.height, 
    this.drawX, this.drawY, this.width, this.height);
于 2013-03-08T15:34:49.313 回答