2d碰撞检测 - 试图获得两个精灵的所有非透明像素

时间:2016-04-10 19:14:23

标签: java sprite collision detection

我正在构建一个2D游戏,我正在尝试实现像素级别/完美碰撞检测。

我的问题是我试图通过使用Buffered Image类getRGB()方法来获取我精灵的所有非透明像素,但是我只能在缓冲图像上使用此方法。

我希望你能指出我正在努力做的事情。以下是我正在进行的游戏课程的方法:

此方法用于获取我的精灵中的所有非透明像素

public HashSet<String> getMask(Sprite character){

HashSet <String> mask = new HashSet<String>();
    int pixel;
    int alpha;

    for(int i = 0; i < character.getWidth(); i++){
        for(int j = 0; j < character.getHeight(); i++){   

            pixel = character.getRGB(i,j);
            alpah = (pixel >> 24) & 0xff;    

            if(alpha != 0){
                mask.add((character.getX + i) + "," + (character.getY - j));
            }
        }
    }
    return mask;
}

检查碰撞的方法

public boolean checkCollision(Sprite a, Sprite b){      
    // This method detects to see if the images overlap at all. If they do,     collision is possible
    int ax1 = a.getX();
    int ay1 = a.getY();
    int ax2 = ax1 + a.getWidth();
    int ay2 = ay1 + a.getHeight();
    int bx1 = b.getX();
    int by1 = b.getY();
    int bx2 = bx1 + b.getWidth();
    int by2 = by1 + b.getHeight();

    if(by2 < ay1 || ay2 < by1 || bx2 < ax1 || ax2 < bx1){
          return false; // Collision is impossible.
    }
    else {// Collision is possible.
        // get the masks for both images
        HashSet<String> maskPlayer1 = getMask(shark);
        HashSet<String> maskPlayer2 = getMask(torpedo);

        maskPlayer1.retainAll(maskPlayer2);  // Check to see if any pixels in maskPlayer2 are the same as those in maskPlayer1

        if(maskPlayer1.size() > 0){  // if so, than there exists at least one pixel that is the same in both images, thus
            System.out.println("Collision" + count);//  collision has occurred.
            count++;
            return true;

        }
    }
    return false;   
}

在上面的getMask()方法中,您可以看到我说:character.getRGB()但是因为字符是Sprite类型我收到错误,因为我只能使用带有缓冲图像的getRGB()。

据我所知,getRGB()很高兴获得缓冲图像在游戏中移动的当前像素,但不乐意获得Sprite的当前像素。我可能误解了这种方法是如何工作的?

所以我想知道是否有任何方法可以解决这个错误,或者如果没有,你能否指出我正确的方向

谢谢大家

1 个答案:

答案 0 :(得分:0)

Sprite是一些扩展Rectangle或具有此类属性的类。

你可以添加一个BufferedImage成员:每当你从角色获得RGB时,你就可以从BufferedImage获得它

int getRGB(int i, int j) {
  return myBufferedImage.getRGB(i, j);
}

你在Sprite中的位置

class Sprite {

  BufferedImage myBufferedImage;


  public int getRGB(int i, int j) {

    ......... as shown above

  }

  ....


}
相关问题