2012-01-11 55 views
2

在cocos2d遊戲開發中,CGRectContainsPoint方法經常用來檢測是否觸碰到CCSprite。如何以方便的方式獲取精靈矩形?

我用代碼fllow得到一個精靈的(這在CCNode)rect屬性

 
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { 
    CCLOG(@"ccTouchEnded"); 
    CGPoint location = [touch locationInView:[touch view]]; 
    location = [[CCDirector sharedDirector] convertToGL:location]; 
    CCLOG(@"location.x:%f, y:%f", location.x, location.y); 
    CGRect rect; 

    rect = CGRectMake(self.firstCard.face.position.x-(self.firstCard.face.contentSize.width/2), self.firstCard.face.position.y-(self.firstCard.face.contentSize.height/2), 
         self.firstCard.face.contentSize.width, self.firstCard.face.contentSize.height); 
    if (CGRectContainsPoint(rect, location)) { 
     CCLOG(@"first card touched"); 
     [firstCard open]; 
    } 

    rect = CGRectMake(self.secondCard.face.position.x-(self.secondCard.face.contentSize.width/2), self.secondCard.face.position.y-(self.secondCard.face.contentSize.height/2), 
         self.secondCard.face.contentSize.width, self.secondCard.face.contentSize.height); 
    if (CGRectContainsPoint(rect, location)) { 
     CCLOG(@"second card touched"); 
     [secondCard open]; 
    } 


} 

我想知道如果有一種方便的方式獲得CCSprite的矩形簡單?

+2

你可以通過精靈值爲[sprite_nm boundingBox的]。方法。我認爲它會對你有用。它返回整個Rect。 – Marine 2012-01-11 05:51:42

回答

2

請使用boundingBox我認爲這將是一個很好的選擇使用。

像這樣:

- (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    locationTouchBegan = [touch locationInView: [touch view]]; 

    //location is The Point Where The User Touched 

    locationTouchBegan = [[CCDirector sharedDirector] convertToGL:locationTouchBegan]; 

    //Detect the Touch On sprite 

    if(CGRectContainsPoint([sprite boundingBox], locationTouchBegan)) 
    { 
     isSpriteTouched=YES; 
    } 

} 
2

Kobold2D有一個方便的方法containsPoint作爲CCNode擴展(的Objective-C類),你可以在你的項目複製:

-(BOOL) containsPoint:(CGPoint)point 
{ 
    CGRect bbox = CGRectMake(0, 0, contentSize_.width, contentSize_.height); 
    CGPoint locationInNodeSpace = [self convertToNodeSpace:point]; 
    return CGRectContainsPoint(bbox, locationInNodeSpace); 
} 

你的代碼,然後被簡化到這一點,它會與旋轉和/工作或縮放的精靈(boundingBox方法無法正確測試旋轉和縮放的精靈)。

if ([firstCard.face containsPoint:location]) { 
     CCLOG(@"first card touched"); 
}