2
public void checkForCollision () {
          
  int headX = cells[0].x; 
  int headY = cells[0].y;
  int noOfParts = nPoints;
  
  for(int i = 1; i <noOfParts;i++)
  {
     int tempX = cells[i].x;
     int tempY = cells[i].y;
     
     
      if(tempX == headX && tempY == headY){
          JOptionPane.showMessageDialog(null,"Head hit body");
          //EndGameCollectScore etc.
        }
  }
       
} 

编辑:'Cells[]' 是 Point 类型的数组,noOfParts 是蛇有多少段

主要问题

使用上面的代码,我试图将 tempX 与 headX 进行比较,但我希望有一定的误差余量,例如 +-5 但我不确定如何实现这一点,我的理由是我在想可能是 x 和Y 变量可能相差几位数,所以如果我有蛇的一段的半径(下面备用中“蛇”的解释),那么如果我是对的并且值有点偏离它应该仍然会出现回正。

或者

选择

如果有人可以提出更好的方法来做到这一点?基本上它是针对蛇游戏的,headX 和 headY 是蛇的头部,而 Cells 中剩余的 X 和 Y 变量是身体,我试图比较头部是否撞到身体。

我测试了它,它似乎可以工作,但是在我再次测试它之后,它似乎只会在我让蛇在自己身上翻倍几个方格时才会发生碰撞。例如,如果我垂直穿过身体,它将不会检测到碰撞。

我也相当肯定,在蛇移动的每个块之后都会调用此方法。

干杯,谢恩。

PS 睡眠很少,血液中的糖分过多,如果您需要进一步澄清,因为上述内容没有多大意义,请告诉我。

4

3 回答 3

10
int eps = 5;
if (Math.abs(tempX - headX) <= eps && Math.abs(tempY - headY) <= eps) { 
    // ...
}
于 2012-11-04T16:13:20.843 回答
3

要检查两个点是否在delta彼此的范围内,请计算它们之间的距离。您可以通过使用正方形来避免进入平方根领域,如下所示:

int distSq = (tempX-headX)*(tempX-headX) + (tempY-headY)*(tempY-headY);
int minDist = 5;
if (distSq < minDist*minDist) {
    // too close
}
于 2012-11-04T16:16:06.830 回答
1

I don't know how your snake looks, but if it has a complex shape, looking for a hit can be expensive in terms of speed. You can speed up collision detection if you can do a quick test, to see if a collision is possible at all. You can do this by using a bounding box. You would have to keep track of minimum and maximum x and y positions of the snake body. Only if a coordinate lies within these boundaries you would take account of the exact shape of the snake. How this has to be done depends on how the snake is represented. Check for each tile or each pixel the snake is made of or possibly check if the coordinate is within a polygon, if the snake outline is defined by a polygon. (I'm not going to explain how this works here, but you will find algorithms if you google a bit.)

If you need to calculate the distance to another point (the snake head), you can use different metrics for this. If only horizontal and vertical movements are possible within the game, the so called Manhattan or taxi distance can be used: d = |x1-x0| + |y1-y0|. It consists of adding the x and y distances, or you can use the maximum of both distances: d = Max(|x1-x0|, |y1-y0|) (correponds to 2kay's approach).

If you need the exact distance, apply the Pythagorean formula. In order to compare the distance with the error margin, you don't need to calculate the square root. Instead compare the square of the distance with the square of the error margin. This saves time. (x1-x0)^2 + (y1-y0)^2 < error_margin^2.

于 2012-11-04T16:30:39.853 回答