2011-05-01 77 views
-1

.M:麻煩與CGRectIntersectsRect行動

-(void)accelerometer:(UIAccelerometer *)accelerometer 
     didAccelerate:(UIAcceleration *)acceleration 
{ 
    if(CGRectIntersectsRect(ball.bounds , fang.bounds)) 
    { 
     UIImage *image = [UIImage imageNamed:@"guy.png"]; 
     UIImageView *imageview = [[UIImageView alloc] initWithImage:image]; 
     [self.view addSubView:imageview]; 
     [imageview release]; 
    } 

    NSLog(@"x : %g", acceleration.x); 
    NSLog(@"y : %g", acceleration.y); 
    NSLog(@"z : %g", acceleration.z); 

    delta.y = acceleration.y * 60; 
    delta.x = acceleration.x * 60; 

    ball.center = CGPointMake(ball.center.x + delta.x, ball.center.y + delta.y); 

    // Right 
    if(ball.center.x < 0) { 
     ball.center = CGPointMake(320, ball.center.y); 
    } 

    // Left 

    if(ball.center.x > 320) { 
     ball.center = CGPointMake(0, ball.center.y); 
    } 

    // Top 

    if(ball.center.y < 0) { 
     ball.center = CGPointMake(ball.center.x, 460); 
    } 

    // Bottom 
    if(ball.center.y > 460) { 
     ball.center = CGPointMake(ball.center.x, 0); 
    } 
} 

.H:

UIImageView *ball; 

IBOutlet UIImageView *fang; 

我的煩惱: 當我打開應用程序,圖像@ 「guy.png」,揭示本身沒有任何接觸方。我需要幫助。 ALSO // 「」 **我的加速度計是SO波濤洶涌,幾乎與此.M代碼工作:

if(CGRectIntersectsRect(ball.bounds , fang.bounds)) 
{ 
    UIImage *image = [UIImage imageNamed:@"endScreenImage.png"]; 
    UIImageView *imageview = [[UIImageView alloc] initWithImage:image]; 
    [self.view addSubView:imageview]; 
    [imageview release]; 
} 

幫助請

回答

3

的幾個問題:

  1. CGRectIntersectsRect()正在恢復YES因爲你正在比較對象的界限,而不是框架。對象的邊界是描述對象如何看待自己尺寸的矩形。它通常起源於(0,0),尺寸是視圖的大小。由於兩個視圖都有一個從(0,0)開始的邊界,所以邊界矩形相交。

    你真正想要的是框架的意見。視圖的框架表示該視圖中佔據的空間,就其超視圖而言。那就是:

    if (CGRectIntersectsRect(ball.frame, fang.frame)) { // etc. }

    幀代表視圖的位置。邊界表示視圖內的內容的位置。當你比較兩個視圖的位置時,你幾乎總是想要使用框架。

  2. 正如目前所寫,您的代碼將在每次有交叉點時添加新的子視圖,但不會刪除舊的子視圖。由於加速度計可以每秒觸發多次,這可能會導致將很多視圖添加到視圖層次結構中。這可能會對性能產生重大影響,並可能是您看到如此糟糕的性能的原因。我會建議改爲創建一個UIImageView作爲實例變量,然後使用hidden屬性來控制它是否可見。

因此,我建議你修改代碼如下:

if (CGRectIntersectsRect(ball.frame, fang.frame)) { 
    guyView.hidden = NO; 
} 
else { 
    guyView.hidden = YES; 
} 
+0

交點代碼是[給出一個答案(http://stackoverflow.com/questions/5845692/action - 碰撞檢測-cgrectintersects正/ 5846475#5846475)到此用戶的早期問題。對問題的好解釋! – 2011-05-01 19:23:58