Reputation: 19727
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.
Upvotes: 1
Views: 664
Reputation: 391
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...
}
Upvotes: 4