检测圆上的触摸点,Cocos2d

时间:2013-01-29 15:52:49

标签: ios objective-c cocos2d-iphone

我在cocos2d中创建了一个带draw功能的圆圈,我试图检测圆圈线上的触摸点,让我们说用户触摸我要打印的圆圈底部270,如果用户触摸圆圈的顶部我想打印90等....

我看过这个问题,但他们首先检测到一个精灵,然后只是比较一下圈内外的触摸

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

how to detect touch in a circle

- (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);
}

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

3 个答案:

答案 0 :(得分:0)

您可以将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");
}

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

答案 1 :(得分:0)

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

我假设你使用how to detect a circle

中的代码

如果触摸在圆圈内,则取圆圈的中心点和触摸点,然后比较两者以查看偏移X和Y是什么。根据X / Y偏移量,您应该能够确定单击圆圈的哪一部分(顶部,左侧,右侧,底部等)。如果你想要角度,找到两点的斜率。

答案 2 :(得分:0)

试试这个,没有测试代码,根据你的需要改进它

-(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;
}