title: Cocos2d handling touch with multiple layers
body: <p>I've been busy for a few days trying to figure out how to handle touch in my Cocos2d project. The situation is a bit different as normal. I have a few different game layers that have items on it that I need to control with touch:</p>
  
  <ul>
  <li>ControlLayer: Holds the game controls
  (movement, action button). This layer is on top.</li>
  <li>GameplayLayer: Holds the game objects
  (CCSprites). This layer is directly beneath the ControlLayer.</li>
  </ul>
  
  <p>Now my touches work fine in the ControlLayer, I can move my playable character around and make him jump and do other silly stuff. Yet I cannot grasp how to implement the touches to some of my CCSprites.</p>
  
  <p>The information I've gathered so far makes me think I need get all my touch input from the control layer. Then I somehow need to 'cascade' the touch information to the GameplayLayer so I can handle the input there. Another option would be for me to get the CGRect information from my sprites by somehow creating an array with pointers to the objects that should be touchable. I should be able to use that information in the ControlLayer to check for each item in that list if the item was touched.</p>
  
  <p>What is the best option to do this, and how do I implement this? I'm kind of new to programming with cocoa and Objective C so I'm not really sure what the best option is for this language and how to access the sprites CGRect information ([mySpriteName boundingBox]) in another class then the layer it is rendered in.</p>
  
  <p>At the moment the only way I'm sure to get it to work is create duplicate CGRects for each CCSprite position and so I can check them, but I know this is not the right way to do it.</p>
  
  <p>What I have so far (to test) is this:
  ControlLayer.m</p>
  
  <pre><code>- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [touches anyObject];
  CGPoint location = [touch locationInView: [touch view]];
  
  CGRect rect = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
  
  //Tried some stuff here to get see if I could get a sprite by tagname so I could use it's bounding box but that didn't work
  
  // Check for touch with specific location
  if (CGRectContainsPoint([tree boundingBox], location)) {
      CCLOG(@"CGRect contains the location, touched!");
  }
  
  CCLOG(@"Layer touched at %@", NSStringFromCGPoint(location));
  </code></pre>
  
  <p>}</p>
  
  <p>Thanks in advance for helping me!</p>