开发者

sample code for collision detection in iPhone sdk

开发者 https://www.devze.com 2023-02-24 07:10 出处:网络
Can you please suggest sample code for collision detection o开发者_StackOverflow中文版f two imageviews.

Can you please suggest sample code for collision detection o开发者_StackOverflow中文版f two imageviews.

Thanks in advance.


You can Detect Collision between two images by making rect for those image views.

Consider my image-views being named: img_view1 and img_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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消