1

I have a CCLayer subclass MyLayer in which I handle touch events:

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

I set the content size of MyLayer instances like this:

`myLayer.contentSize = CGSizeMake(30.0, 30.0);`

I then add MyLayer instances as children of ParentLayer. For some reason I can tap anywhere on the screen and a MyLayer instance will detect the tap. I want to only detect taps on the visible portion/content size. How can I do this?

Are the MyLayer instances somehow inheriting a "tappable area" from somewhere else? I've verified that the contentSize of the instance just tapped is (30, 30) as expected. Perhaps the contentSize isn't the way to specify the tappable area of CCLayer subclass.

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

1 Answers1

4

When the touch is enabled on a particular CCLayer, it receives all of the touch events in the window. That being said, if there are multiple layers, all layers will receive the same touches.

To alleviate this, obtain the location from the UITouch, convert it to Cocos2d coordinates, then check to see if it is within the bounds of the Layer you are concerned with.

Here's some code to work with:

CCLayer * ccl = [[CCLayer alloc] init];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint(CGRectMake(ccl.position.x - ccl.contentSize.width/2, ccl.position.y - ccl.contentSize.height/2, ccl.contentSize.width, ccl.contentSize.height), location)) {
   //continue from there...
}
bendu
  • 391
  • 4
  • 15
  • That's interesting. I'm surprised a `CCLayer` would receive touches outside of it's contentSize. – SundayMonday Apr 15 '12 at 02:49
  • 1
    It is a bit strange, I agree. However, CCLayers can be quite complex to determine the location of when they are nested in each other. This is probably to keep the main thread available to graphics processing. – bendu Apr 15 '12 at 02:51