Search code examples
iphonecocos2d-iphonecollision-detectionobjective-c++

How to determine quickly if the user touched one of many CGRects


I have an iPhone game, where there might be 30 (or more) CGRects and I need a quick way of determining if the user touched one. I have been previously been considering using the follow setup to detect if the user touched a CGRect in Cocos2d inside of touches began. So I have a vector (I am using Obj-C++) of CGRects:

for (int i = 0; i < (int) vec_of_cgrects; i++) {
    if (CGRectContainsPoint(vec_of_cgrects[i], location) {
        //Do what I need to do if user touches one of the rectangles
    }
}

But this isn't that efficient and I am wondering if this the best way to detect if the user touched a specific rect of a vector of rectangles or if there is a better way.


Solution

  • Do you want something to happen for each rectangle that the user touches, or one event should the user touch any old rectangle?

    One improvement you can make in both situations is to sort your CGRects by their x-coordinate (or y-coordinate if that suits your circumstances more), so you can break as soon as the CGRect's x-coordinate is greater than the touch's x-coordinate.

    If the latter, you can also check beforehand to see if any CGRect is fully contained by other CGRects and if so, remove them from the array.