Search code examples
cocos2d-xcollision-detection

convertToNodeSpace confusion


I try to capture intersectsRect between 2 sprites after reading this :
http://www.cocos2d-x.org/wiki/Coordinate_System#convertToNodeSpace
i have this hierarchy of sprites

+Root 
|-Child_1
|     |--Child_1_of_Child_1
|-Child_2

in code its simple

Sprite* root = Sprite::create();
Sprite* Child_1 = Sprite::create();
Sprite* Child_1_of_Child_1 = Sprite::create();
Sprite* Child_2 = Sprite::create();

root->addChild(Child_1);
Child_1->addChild(Child_1_of_Child_1 );
root->addChild(Child_2);

i want to capture collision between Child_2 and Child_1_of_Child_1 sprites. but what every i do its never capture it in the Child_1_of_Child_1 this is what i have in the update loop.

        Rect r = Child_2->getBoundingBox();
        Vec2 vr = Child_2->getPosition();
        Vec2 newNodeSpaceVec =  Child_1->convertToNodeSpace(vr);
//not working also 
// Vec2 newNodeSpaceVec =  Child_1->Child_1_of_Child_1->convertToNodeSpace(vr);
        Rect NewRec(newNodeSpaceVec.x,newNodeSpaceVec.y,r.size.width,r.size.height);

        //THIS iS ALLWAYS FALSE 
        if(Child_1->Child_1_of_Child_1->getBoundingBox().intersectsRect(NewRec))
    {
    }

now matter what i do even if i see the 2 sprites collide the if is never true.


Solution

  • For the structure you presented, try to use this:

    Vec2 child1Pos = Child_1->getParent()->convertToWorldSpace(Child_1->getPosition());