Search code examples
buttoncocos2d-iphonetouchextendarea

cocos2d extend touch area from a button


I got some radiobuttons but the toucharea is to small. The toucharea depends on the image size. Is there an elegant way to extend the touch area with cocos2d without using a bigger image or make my own touch areas with cgrect? setContentSize do what I want. Unfortunately the image moves to the left bottom corner of the contentsize. Set the anchorpoint moves the contentsize around but the image stays in the left bottom corner.

    CCMenuItem* pickEasy = [CCMenuItemImage itemFromNormalImage:@"radiobutton_off.png" selectedImage:@"radiobutton_on.png" target:self selector:@selector(pickEasyTapped:)];
    pickEasy.position = ccp(ss.width * 0.40, ss.height * 0.78);
    [pickEasy setContentSize:CGSizeMake(50, 50)];

Thanks in advance.


Solution

  • You need to override the rectInPixels method

    - (CGRect)rectInPixels
    {
    CGSize s = [self contentSize];
    return CGRectMake(0, 0, s.width, s.height);
    }
    
    - (BOOL)containsTouchLocation:(UITouch *)touch
    {   
    CGPoint p = [self convertTouchToNodeSpace:touch];
    CGRect r = [self rectInPixels];
    return CGRectContainsPoint(r, p);
    }
    
    - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    
    NSSet *allTouches = [event allTouches];
    for (UITouch *aTouch in allTouches) {
    
            if ( ![self containsTouchLocation:aTouch] ) return NO;
    }
    
    return YES;
    }
    

    This just tells the sprite to check that the touch lyes within your altered CGRect

    Edit to show CCSprite subclass ---

    - (void)onEnter
    {
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
    [super onEnter];
    }
    
    - (void)onExit
    {
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
    }