检测圆上的触点,Cocos2d

我在cocos2d中创build了一个带有drawfunction的圆圈,我试图检测圆圈上的触点,让用户触摸我想要打印的圆圈底部270,如果用户触摸圆圈的顶部,我要打印90等。 …

我已经看过这个问题,但他们先检测一个精灵,然后比较一下,如果接触内部或外部的圆圈

http://www.cocos2d-iphone.org/forum/topic/21629

如何在圈内检测触摸

 - (void) draw { CGSize winSize = [[CCDirector sharedDirector] winSize]; glLineWidth(10.0f); ccDrawColor4F(0.2f, 0.9f, 0.02f, 0.6f); CGPoint center = ccp(winSize.width*0.88, winSize.height*0.8); CGFloat radius = 100.f; CGFloat angle = 0.f; NSInteger segments = 100; BOOL drawLineToCenter = YES; ccDrawCircle(center, radius, angle, segments, drawLineToCenter); } 

如何检测圆形线上的触点?

试试这个,没有testing代码,根据你的需要进行了改进

 -(BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)event { CGSize winSize = [[CCDirector sharedDirector] winSize]; CGPoint location = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]]; CGPoint center=ccp(winSize.width*0.88, winSize.height*0.8); //now test against the distance of the touchpoint from the center change the value acording to your need if (ccpDistance(center, location)<100) { NSLog(@"inside"); //calculate radians and degrees in circle CGPoint diff = ccpSub(center, location);//return ccp(v1.x - v2.x, v1.y - v2.y); float rads = atan2f( diff.y, diff.x); float degs = -CC_RADIANS_TO_DEGREES(rads); switch (degs) { case -90: //this is bottom break; case 90: //this is top break; case 0: //this is left side break; case 180: //this is right side break; default: break; } } return YES; } 

如果你知道中心点和触摸位置,你应该知道你需要知道它在圆上的位置。

我假设你使用如何检测一个圆的代码

如果触摸在圆圈内,则取圆圈的中心点,然后将触点相比较,看看偏移量X和Y是多less。 基于X / Y偏移量,你应该能够找出圆的哪一部分(顶部,左侧,右侧,底部等)被点击了。 如果你想要的angular度,find两个点的斜率。

您可以添加ccTouchBegan/Moved/Ended到您的自定义CCNode :::

 - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { NSLog(@"ccTouchBegan Called"); if ( ![self containsTouchLocation:touch] ) return NO; NSLog(@"ccTouchBegan returns YES"); return YES; } - (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint touchPoint = [touch locationInView:[touch view]]; touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint]; NSLog(@"ccTouch Moved is called"); } - (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { NSLog(@"ccTouchEnded is called"); } 

然后像处理CCSprite一样处理touch (即,计算触摸和center之间的距离并确定触摸是否属于该圆圈)。