Cocos2dx 像素碰撞检测

  public boolean isCollision(int thisLeft, int thisTop, int thisRight, int thisBottom, int otherLeft, int otherTop, int otherRight, int otherBottom) {
  //如果图片不相交的话,不进行像素碰撞检测
  if (thisLeft > otherRight || thisTop > otherBottom || otherLeft > thisRight || otherTop > thisBottom) {
   return false;
  }
  
  //计算相交区域的矩形的左上角和右下角坐标,以及矩形的宽度和高度
  int intersectLeft = thisLeft > otherLeft ? thisLeft : otherLeft;
  int intersectTop = thisTop > otherTop ? thisTop : otherTop;
  int intersectRight = thisRight < otherRight ? thisRight : otherRight;
  int intersectBottom = thisBottom < otherBottom ? thisBottom : otherBottom;
  int intersectWidth = intersectRight - intersectLeft;
  int intersectHeight = intersectBottom - intersectTop;
  
  //计算图片相对于相交区域的偏移量(每张图片要去的相交区域的ARGB数据,其实最重要的还是取得A)
  int thisImageXOffset = intersectLeft - thisLeft;
  int thisImageYOffset = intersectTop - thisTop;
  int otherImageXOffset = intersectLeft - otherLeft;
  int otherImageYOffset = intersectTop - otherTop;
  
  //进行像素碰撞检测
  boolean isCollide;
  isCollide = doPixelCollision(thisImageXOffset, thisImageYOffset, otherImageXOffset, otherImageYOffset, down, blackHole, intersectWidth, intersectHeight);
  return isCollide;
 }

 //(算法思路:取得两张图片的相交区域的ARBG数据,然后取得的A(透明色)的数据,如果两张图片的A的数

//据都不等于0则说明碰上了)
 private boolean doPixelCollision(int firstImageXOffset, int firstImageYOffset, int secondImageXOffset, int secondImageYOffset,
   Image firstImage, Image secondImage, int intersectWidth, int intersectHeight) {
  int numPixels = intersectHeight * intersectWidth;
  int[] argbData1 = new int[numPixels];
  int[] argbData2 = new int[numPixels];
  
  firstImage.getRGB(argbData1, 0, intersectWidth, // scanlength = width
    firstImageXOffset, firstImageYOffset, intersectWidth, intersectHeight);
  secondImage.getRGB(argbData2, 0, intersectWidth, secondImageXOffset, secondImageYOffset, intersectWidth, intersectHeight);
  
  //像素碰撞检测
  for (int row = 0; row < intersectHeight; row++) {
   for (int col = 0; col < intersectWidth; col++) {
    if ((argbData1[row * intersectWidth + col] & 0xff000000) != 0 && (argbData2[row * intersectWidth + col] & 0xff000000) != 0) {
     return true;
    }
   }
  
  
  return false;
 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值