I am creating a toggle switch. I have a CCScene containing a CCLayer containing a ToggleNode. The ToggleNode shows properly with the sprites and labels I put in. The touch handling is not working because the ToggleNode’s bounding box seems to remain zero. I catch the touch in the CCLayer (which works as the ccTouchBegan:withEvent: is being entered) and there I have this code:
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
NSLog(@"bounding box: %f, %f, %f, %f", toggleNode.boundingBox.origin.x, toggleNode.boundingBox.origin.y, toggleNode.boundingBox.origin.x + toggleNode.boundingBox.size.width, toggleNode.boundingBox.origin.y + toggleNode.boundingBox.size.height);
NSLog(@"touch: %f, %f", touchLocation.x, touchLocation.y);
if (CGRectContainsPoint(toggleNode.boundingBox, touchLocation)) {
[toggleNode toggle];
}
return NO;
}
A touch on the ToggleNode results in:
bounding box: 512.000000, 384.000000, 512.000000, 384.000000
touch: 508.000000, 378.000000
Which makes me believe the bounding box remains zero. But why? A retain problem? I am still learning in cocos2d but I do not think this is normal behavior.
If ToggleNode is derived from CCNode, this behavior is normal. A CCNode has a 0-sized bounding box and the contentSize property is also zero.
If you derive your class from CCNode, it’s up to you to set the contentSize property (this also updates the bounding box) to whatever size it should have.
Only if you use a class that use a texture (CCSprite, CCLabelTTF and others) does cocos2d set the contentSize by itself.