Game Development Reference
In the second half, the actual node being iterated is checked. This performs the actual
hit test by first making sure you're not testing a CCScene or CCLayer class node.
The reason is that they both typically have their boundingBox set to the entire
screen area. If you'd test any of these classes, you'd always “hit” them, and that's ex-
actly what you're trying to avoid.
Now that you're sure the test is on a node with a reasonable bounding box, the actual
check is as simple as testing for whether the point is inside the boundingBox :
hit = CGRectContainsPoint(node.boundingBox, point);
Again, if there was a hit, the loop aborts, and the method returns. This is an optimiza-
tion because you only ever need to find any node that responds positively to the hit test.
Obviously, this solution has some drawbacks. For one, it assumes that a node should
get a touch event if the touch is inside its boundingBox . What it doesn't know is
whether there's some kind of game state that would prevent the node from processing
the touch—for example, if the node is a CCMenuItem that's currently disabled. Or if
the touch is on a sprite that actually performs a pixel-perfect collision check; in that
case, the bounding box check is too broad. Moreover, the boundingBox is excess-
ively large when the node is rotated because it's an axis-aligned bounding box that
changes in size as the node rotates.
What you can do to alleviate this situation is add a hitTest method to a CCNode
class category, which performs just the bounding box check by default but can be over-
ridden by subclasses to perform more accurate or conditional checks.
Sandwiching the cocos2d View
Just to complete this test, I'd like to add another text field—but in front of the cocos2d
view so that you truly have a sandwiched cocos2d view with UIKit views in the back
and in the front, and all of them can respond to touches.
The change is rather simple; just add this code at the end of the addSomeTex-
tFields method and make sure you add the textFieldFront as subview of the
window and not the glView :