简体   繁体   English

iPhone sdk中用于碰撞检测的示例代码

[英]sample code for collision detection in iPhone sdk

Can you please suggest sample code for collision detection of two imageviews. 你能否建议两个图像视图的碰撞检测示例代码。

Thanks in advance. 提前致谢。

You can Detect Collision between two images by making rect for those image views. 您可以通过为这些图像视图制作rect来检测两个图像之间的碰撞。

Consider my image-views being named: img_view1 and img_view2 . 考虑我的图像视图命名: img_view1img_view2

Image-views creation: 图像视图创建:

//For img_view1 rect
//parameters are x,y,width,height
CGRect image_rect1 = CGRectMake(img_view1.position.x,img_view1.position.y,100,100);

//For img_view2 rect
//parameters are x,y,width,height
CGRect image_rect2 = CGRectMake(img_view2.position.x,img_view2.position.y,100,100);

Collision detection: 碰撞检测:

if(CGRectIntersectsRect(image_rect1, image_rect2))
{
    NSLog(@"Rect is Intersecting");
}

Nice answere @Anish, however you dont really need to create a new CGRect for the views as you can simply use their respective frame properties. 很好的回答@Anish,但你真的不需要为视图创建一个新的CGRect ,因为你可以简单地使用它们各自的frame属性。

If you want to put that logic in a method it would look like this: 如果你想把这个逻辑放在一个方法中,它将如下所示:

-(BOOL)viewsDoCollide:(UIView *)view1 :(UIView *)view2{
    if(CGRectIntersectsRect(view1.frame, view2.frame))
    {
        return YES;
    }
    return NO;
}

Simply pass the two views you want to test into this method, and check the output result. 只需将要测试的两个视图传递给此方法,然后检查输出结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM