我试图随机选择一个带有值的语句,这些语句从精灵表中的某个点开始绘制。这是我目前的代码。
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.height,
this.drawX,this.drawY,this.width,this.height);
this.checkEscaped();
答案 0 :(得分:2)
Math.floor(Math.random()*7+1)
可以取值1到7.删除+1
。
答案 1 :(得分:0)
我认为您的绘图代码可能有问题:
this.drawX -= this.speed;
ctxEnemy.drawImage(imgSprite,
this.srcX+this.width,this.srcY,this.width,this.height,
this.drawX,this.drawY,this.width,this.height);
this.checkEscaped();
在一行中:this.srcX+this.width,this.srcY,this.width,this.height,
您正在将对象宽度添加到源位置。我想这可能会抛弃你的精灵画。请参阅下面的参考评论示例:
// 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);