如何检测圆圈中的触摸

时间:2011-10-08 13:26:54

标签: cocos2d-iphone

我真的很有帮助。我有点困惑。 我有一个圆形精灵,这个代码

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{

CGSize winSize =[[CCDirector sharedDirector] winSize];
UITouch* myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

CCSprite *circleSprite = (CCSprite*)[self getChildByTag:30];
CGRect correctColorSprite1 = [circleSprite boundingBox];

   if (CGRectContainsPoint(correctColorSprite1, location)) {
   NSLog(@"inside");

}

因为我知道有一个边界框,当我稍微触摸顶部圆圈时,它仍会检测到触摸。

我在一些论坛上读过我需要检测精灵中心和触摸点的距离。但我真的不知道如何编写该代码。我的圈子大小约为50分。

我希望有人能帮助我,给我一些改进代码的片段,以便仅在圈子中检测触摸。没有边界框。你的帮助非常充实。

1 个答案:

答案 0 :(得分:1)

试试这个:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{

CGSize winSize =[[CCDirector sharedDirector] winSize];
UITouch* myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

CCSprite *circleSprite = (CCSprite*)[self getChildByTag:30];
//CGRect correctColorSprite1 = [circleSprite boundingBox];
CGRect correctColorSprite1 = CGRectMake(
    circleSprite.position.x - (circleSprite.contentSize.width/2), 
    circleSprite.position.y - (circleSprite.contentSize.height/2), 
    circleSprite.contentSize.width, 
    circleSprite.contentSize.height);

//find the center of the bounding box
CGPoint center=ccp(correctColorSprite1.size.width/2,correctColorSprite1.size.height/2);

//now test against the distance of the touchpoint from the center
   if (ccpDistance(center, location)<50) 
   {
     NSLog(@"inside");

   }
}