iOS中不均匀形状的碰撞检测 [英] Collision detection of uneven shapes in iOS

查看:275
本文介绍了iOS中不均匀形状的碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨大家好,

我正在为iPad进行拖放活动。我有一个矩形的.png图像(参见名为obj2的图像)。当我将obj1仅拖动到矩形的黑色部分时,它应该做出反应。

I am working on drag and drop activity for iPad. I have a rectangle .png image (see the image named as obj2). When I drag obj1 only on the black portion of the rectangle thn it should react.

if (CGRectIntersectsRect(obj1.frame, obj2.frame))
{
    NSLog(@" hit test done!! ");
}

现在,即使在透明区域,这段代码也会进行热门测试。如何防止这种情况发生?

Right now, this piece of code takes hit test even on the transparent area. How to prevent that to happen?

提前致谢。

问候,
Ranjan

Regards, Ranjan

推荐答案

对于像您的具体示例(三角形和圆形)这样简单的事情,DavidRönnqvist提供的链接非常有用。你应该看看它看到一些可用的工具。但对于一般情况,最好的选择是剪裁,绘图和搜索。

For something as simple as your specific example (triangle and circle), the link that David Rönnqvist gives is very useful. You should definitely look at it to see some available tools. But for the general case, the best bet is clipping, drawing, and searching.

有些背景,请参阅将CGRRect剪辑为CGPath

首先,创建一个仅限alpha的位图图片。这在上面的链接中有解释。

First, create an alpha-only bitmap image. This is explained in the above link.

接下来,使用 CGContextClipToMask()将你的上下文剪辑到你的一个图像。

Next, clip your context to one of your images using CGContextClipToMask().

现在,将您的其他图像绘制到上下文中。

Now, draw your other image onto the context.

最后,在位图数据中搜索任何颜色像素(请参阅上面的链接,例如代码)。

Finally, search the bitmap data for any colored pixels (see the above link for example code).

如果任何像素着色,则会有一些重叠。

If any of the pixels colored, then there is some overlap.

另一种类似的方法(可能实际上更快)是将每个图像绘制到自己的仅alpha CGBitmapContext中。然后遍历每个上下文中的像素,看看它们是否同时都是> 128.

Another, similar approach (which might actually be faster), is to draw each image into its own alpha-only CGBitmapContext. Then walk the pixels in each context and see if they ever are both >128 at the same time.

这篇关于iOS中不均匀形状的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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