2013-08-07 135 views
1

我在迷宫游戏中工作的HTML 5借鉴了HTML5画布的X形状,并带有边框

这里碰撞检测是我用画布上画一个“X”的功能(使用触摸板,用户将通过迷宫导航X)。

dim = 8; 

function rect(x,y,xdim){ 
    ctx.beginPath(); 
    ctx.moveTo(x - xdim, y - xdim); 
    ctx.lineTo(x + xdim, y + xdim); 
    ctx.moveTo(x + xdim, y - xdim); 
    ctx.lineTo(x - xdim, y + xdim); 
    ctx.strokeStyle = '#FF5000'; 
    ctx.stroke();  
} 

的问题是在checkcollision功能,主要是在这段代码:

ctx.getImageData(checkx, checky, 16, 16); 

我正在寻找最佳的方法来检查所有被采取了由空间画布上的“X”。

在我使用的代码中有更多评论。

问题: 1.有时,X去一点点通过边境 2.有时,X不亲近,让它和边界之间的几个像素。

function checkcollision(checkx, checky){ 
     var collision = 0; 
     /* 
      User presses an arrow key 

      Calculate where that would move the square to. 

      Look at all of the pixels on the maze image that the square will cover 
      in its new position (our square is 15x15 so we look at 225 pixels) 

      Are any of the pixels black (the maze is white with black borders. 
      If a pixel is black that means the square would collide with a border) 

      YES: then do not move 

      NO: then move 
     */ 
     var imgd = ctx.getImageData(checkx, checky, 15, 15); 
     pix = imgd.data; 
     for (var i = 0; n = pix.length, i < n; i += 4){ 
      if (pix[i] == 0) { 
       collision = 1; 
      } else if(pix[i] == 255 && pix[i + 1] == 0){ 
       winner = "yes"; 
      } 
     } 
     return collision; 
    } 

我相信getImageData得到一个矩形,它从角落中的x,y位置开始。

因此,也许有一种方法使用checkx和checky为中心坐标绘制和检索16个像素宽的方形

+0

我相信getImageData会得到一个矩形,它从角落中的x,y位置开始。所以也许有一种方法可以使用checkx和checky作为中心的坐标来绘制它,并检索一个16像素宽的正方形。 –

回答

-1

哇,写的问题说得很清楚:

var imgd = ctx.getImageData(checkx - xdim, checky - xdim, 16, 16); 

Ty guys