像素完美的碰撞检测 Android [英] Pixel-Perfect Collision Detection Android

查看:32
本文介绍了像素完美的碰撞检测 Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在开发一款 Android 游戏.我需要实现像素完美碰撞检测.我已经在每个图像周围设置了边界框,每个边界框都经过转换以匹配图像的当前旋转.这一切都很好.我还将每个位图中的像素数据存储在一个数组中.有人可以帮我找出检测像素是否重叠的最有效方法吗?在此先感谢您的帮助!

Ok so I am working on a game on Android. I need to implement pixel perfect collision detection. I already have the bounding boxes set up around each of the images, each bounding box is transformed to match the current rotation of the image. That all works great. I also have the pixel data from each bitmap stored in an array. Can someone help me figure out the most efficient way to go about detecting if the pixels overlap? Thanks in advance for any help!

推荐答案

基本思想是为每个对象创建一个位掩码,您可以在每个像素中指示该对象是否实际存在.然后比较两个对象的位掩码的每个像素.

The basic idea is to create a bitmask for each object where you indicate in each pixel if the object is actually there or not. Then you compare each pixel of the bitmasks for the two objects.

您可以通过计算两个边界框重叠的矩形区域来最小化需要检查的像素数.该区域内的像素是您需要检查的.

You could minimize the number of pixels you need to check by calculating the rectangular area in which the two bounding boxes overlap. The pixels within this area are what you need to check.

遍历所有这些像素,并检查两个对象中是否都填充了像素.如果它们中的任何一个是,那么你就会发生碰撞.

Iterate through all of those pixels, and check if the pixel is filled in both objects. If any of them are, then you have a collision.

如果您的矩形与 x/y 轴对齐,要找到重叠部分,请找到重叠部分的左侧、右侧、顶部和底部.它看起来像这样(我本可以搞砸边缘情况,还没有尝试过):

If your rectangles are aligned with the x/y axis, to find the overlap, find the left, right, top and bottom of the overlap. It would look something like this (I could have screwed up the edge cases, haven't tried this):

int left = max(obj1.left, obj2.left)
int right = min(obj1.right, obj2.right)
int top = min(obj1.top, obj2.top)
int bottom = max(obj1.bottom, obj2.bottom)

for (int x = left; x < right; x++) {
  for (int y = top; y < bottom; y++) {
     if (obj1.isFilled(x,y) && obj2.isFilled(x,y)) {
        return true;
     }
  }
}

这篇关于像素完美的碰撞检测 Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆