2011-11-05 34 views
0

好吧,我最後一次嘗試了這個,它太模糊,所以我會再試一次。我正在製作一個自上而下的透視iPhone遊戲,有一個mainSprite(一個UIImageView),它將與另一個UIImageView相沖突。當它發生時,我希望mainSprite停止移動。基本上創造一堵牆。那有意義嗎?我沒有使用任何框架,如cocos2d。我知道CGRectIntersectWithRect方法,我的問題是我需要在該方法中放置什麼。我沒有任何其他變量,例如速度或速度,只是會在屏幕上移動精靈的按鈕。這是我的代碼。iPhone遊戲開發,碰撞檢測,創造了牆效應

這是用於在屏幕上移動精靈的.m代碼。

-(void)goDown{ 
mainSprite.center = CGPointMake(mainSprite.center.x, mainSprite.center.y+5); 
} 

-(IBAction)down{ 
    [self downAnimation]; 
    goDown = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(goDown) userInfo:nil repeats:YES]; 
    if (goDown == nil) { 
     goUp = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(goDown) userInfo:nil repeats:YES]; 

    } 
} 

這裏是我已建立了碰撞的方法:

-(void)collision { 
    if (CGRectIntersectsRect(mainSprite.frame, collisionImage.frame)) { 

    } 
} 

幫助將不勝感激。

回答

1

你可以做什麼是添加上的對象是否已經相撞布爾(我建議作爲一個實例變量)

有了這個當rects有相交

,你可以將它設置爲YES在您的倉庫方法,你會再查布爾,如果布爾爲是,則不會改變中心,否則繼續改變它

每次-goDown被稱爲添加在檢查碰撞

這樣,如果它已經發生了碰撞,你可以實際上停用該定時器,使其不再停機,或者你可以按照上面提到的布爾方式來實現。

我建議作出與當前中心的一個論據碰撞檢查方法,以便您可以檢查是否將5與中心的y會使其發生碰撞,因此您可以禁用定時器/停止加5正確的,因爲它發生碰撞,而不是之後

- (void)goDown { 
    float delta = [self checkCollision]; 
    mainSprite.center = CGPointMake(mainSprite.center.x, mainSprite.center.y + delta); 
} 

- (float)checkCollision { 
    CGRect testFrame = CGRectMake(mainSprite.frame.origin.x, mainSprite.frame.origin.y + 5.0f, mainSprite.frame.size.width, mainSprite.frame.size.height); 
    if (CGRectIntersectsRect(testFrame, collisionImage.frame)) { 
     return 0.0f; 
     // stop the sprite from moving anymore so it doesn't actually intersect, just stops "on top" 
    } 
    return 5.0f; 
    // if they have not collided then just continue on your way 

的代碼示例實際顯示沒有我的方法上面

什麼,我在這裏做的是檢查是否有衝突,如果那裏有將要發生碰撞,然後停止添加任何到中心,否則它會繼續添加到中心座標

+0

這很有道理,但你能告訴我如何重置mainSprite位置到其他UIImageView之外嗎? –

+0

你的意思是在另一個之外? – DanZimm

+0

就像mainSprite與UIImageView相撞時,我需要寫什麼代碼才能將mainSprite保留在UIImageView之外,從而創建牆效果? –