在cocos2d游戏开发中, CGRectContainsPoint 方法通常用于检测是否触摸CCSprite。
我使用代码fllow来获取sprite(在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的直接直截了当?
答案 0 :(得分: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");
}
答案 1 :(得分: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;
}
}