簡體   English   中英

如何找出兩個物體是否相互交叉?

[英]How to find whether two objects intersect each other?

我使用以下代碼來創建對象並為其設置動畫

//For creating two imageview 
UIImageView *bbl1Obj=[[UIImageView alloc]initWithFrame:CGRectMake(34,77,70, 70)];
bbl1Obj.image=[UIImage imageNamed:@"bubble1.png"];
[self.view addSubview:bbl1Obj];
UIImageView *bbl2Obj=[[UIImageView alloc]initWithFrame:CGRectMake(224,77,70, 70)];
bbl2Obj.image=[UIImage imageNamed:@"bubble2.png"];
[self.view addSubview:bbl2Obj];
// for animating the objects
[UIImageView beginAnimations:nil context:NULL];
[UIImageView setAnimationDuration:3];
[bbl1Obj setFrame:CGRectMake(224,77,70, 70)];
[UIImageView commitAnimations];

[UIImageView beginAnimations:nil context:NULL];
[UIImageView setAnimationDuration:3];
[bbl2Obj setFrame:CGRectMake(34,77,70, 70)];
[UIImageView commitAnimations];

我想在兩個圖像相互交叉時顯示圖像。 但我不知道如何在動畫時找到圖像是否相交。 任何人都可以告訴我如何在動畫時找到兩個圖像是否相互交叉。

提前致謝

這是我通常用來測試交叉口的東西。 但是,我不確定它是否適用於動畫中期。

if(CGRectIntersectsRect(bbl1Obj.frame, bbl2Obj.frame)) {

    //They are intersecting
}

它在當前動畫時不適用於測試交叉點,請嘗試使用視圖圖層的presentationLayer屬性。 以下是presentationLayer內容,取自CALayer類參考:

表示層

返回包含當前事務開始時所有屬性的圖層副本,並應用任何活動動畫。

考慮到這一點,您現在可以嘗試:

CALayer *bbl1ObjPresentationLayer = (CALayer*)[bb1Obj.layer presentationLayer];
CALayer *bbl2ObjPresentationLayer = (CALayer*)[bb2Obj.layer presentationLayer];

if(CGRectIntersectsRect(bbl1ObjPresentationLayer.frame, bbl2ObjPresentationLayer.frame)) {

    //They are intersecting
}

因此,如果第一種方式不起作用,第二種方式肯定會。

使用CGRectContainsPoint賦予對象相交。

    if(CGRectContainsPoint([bbl1Obj bounds], CGPointMake(bbl2Obj.frame.origin.x, bbl2Obj.frame.origin.y)))
    {
NSLog(@"intersect");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM