ccTouchBegin触摸点未正确读取

时间:2011-11-25 13:33:20

标签: objective-c ios cocoa-touch ios4 cocos2d-iphone

我制作了这个ccTouchBegin方法:

- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {



    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    CGPoint pos = [self getChildByTag:1].position;


    CGSize size = [self getChildByTag:1].contentSize;
    float padding = 3;
    float w = size.width+padding*2;
    float h = size.height+padding*2;

    // first row
    CGRect rect1 = CGRectMake(pos.x-w/2, pos.y-h/2, w/3, h/3);
    CGRect rect2 = CGRectMake(pos.x-(w*(2/3)/2), pos.y-h/2, w/3, h/3);
    CGRect rect3 = CGRectMake(pos.x+(w*(2/3)/2), pos.y-h/2, w/3, h/3);
    //second row
    CGRect rect4 = CGRectMake(pos.x-w/2, pos.y-(h*(2/3)/2), w/3, h/3);
    CGRect rect5 = CGRectMake(pos.x-(w*(2/3)/2), pos.y-(h*(2/3)/2), w/3, h/3);
    CGRect rect6 = CGRectMake(pos.x+(w*(2/3)/2), pos.y-(h*(2/3)/2), w/3, h/3);
    //third  row
    CGRect rect7 = CGRectMake(pos.x-w/2, pos.y+(h*(2/3)/2), w/3, h/3);
    CGRect rect8 = CGRectMake(pos.x-w/2, pos.y+(h*(2/3)/2), w/3, h/3);
    CGRect rect9 = CGRectMake(pos.x-w/2, pos.y+(h*(2/3)/2), w/3, h/3);


    if (CGRectContainsPoint(rect1, location)) {
        NSLog(@"rect1");
    } else if (CGRectContainsPoint(rect2, location)) {
        NSLog(@"rect2");
    } else if (CGRectContainsPoint(rect3, location)) {
        NSLog(@"rect3");
    } else if (CGRectContainsPoint(rect4, location)) {
        NSLog(@"rect4");
    } else if (CGRectContainsPoint(rect5, location)) {
        NSLog(@"rect5");
    } else if (CGRectContainsPoint(rect6, location)) {
        NSLog(@"rect6");
    } else if (CGRectContainsPoint(rect7, location)) {
        NSLog(@"rect7");
    } else if (CGRectContainsPoint(rect8, location)) {
        NSLog(@"rect8");
    } else if (CGRectContainsPoint(rect9, location)) {
        NSLog(@"rect9");
    }

    return YES;
}

它很简单,需要触摸点,然后获取子项的内容和位置,并将子项所在的位置分开以形成3x3表。但是现在它不起作用,即使我尝试触摸整个屏幕,我也没有得到任何NSLog。任何想法都错了吗?

1 个答案:

答案 0 :(得分:2)

  1. Learn how to set a breakpoint。断点允许您立即测试是否正在执行方法或代码行。
  2. 除非您使用CCTargetedTouchHandler作为CCLayer中触摸的默认处理程序,否则不会调用ccTouchBegan方法。为此,请覆盖CCLayer类中的registerWithTouchDispatcher,但不要调用超级实现:

  3. -(void) registerWithTouchDispatcher
    {
      [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self 
                                                       priority:0
                                                swallowsTouches:NO];
    }
    

    您无需删除该委托。 CCLayer类为您处理。