3
\$\begingroup\$

Is there a method in Cocos2d like CGRectIntersectsRect, except instead of limiting it to one sprite, it checks for ALL objects?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

What you can do is get all the children in the current layer and then iterate through then and use the CGRectIntersectsRect function to check if the any node is present at your desired location.

After that you can do what ever you want to do with the nodes that are present at that frame.

You need to get all the nodes like this

CCArray *childrenNodes = [self children];

and check for intersection like this

for(CCNode *someNode in childrenNodes)
{
    CGRect rect = ((CCSprite *)someNode).textureRect;
    if(CGRectIntersectsRect(rect, desiredRect))
    {
        // --------------------->Do something
    }
}

Edit:
As mentioned in your below comment you can modify the above code to only check for a particular type of sprite or sprites. For this to happen you need to subclass ccsprite or give a tag to a set of sprite representing a particular type of object, then in the for loop only check for that sprite or sprites depending on your requirement.

for(CCNode *someNode in childrenNodes)
{
    if([someNode isKindOfClass:YourSpriteClass] || someNode.tag == 81)
        continue;
    CGRect rect = ((CCSprite *)someNode).textureRect;
    if(CGRectIntersectsRect(rect, desiredRect))
    {
        // --------------------->Do something
    }
}

I think you will get the idea from the above code.

\$\endgroup\$
2
  • \$\begingroup\$ But what about the other children in the room? What if I just wanted it to be for one type of object, like a wall, but not, say, a tree? \$\endgroup\$
    – Someone
    Feb 20, 2012 at 16:41
  • \$\begingroup\$ hey @JackStone Did you try out the code with the changes that i made in my answer. \$\endgroup\$
    – Robin
    Feb 27, 2012 at 8:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .