@grimfate
I want to detect collide between 2 sprites: “Child_1_of_Child_1” and “Child_2” , but rectIntersectRect don´t work, i am very confused
I read some solution in c++, but i need in javascript.
+Root
|-Child_1
| |–Child_1_of_Child_1
|-Child_2
var Child_1 = new cc.Sprite(res.Child_1_png);
Child_1.setPosition(100,100);
this.addChild(Child_1);
var Child_1_of_Child_1 = new cc.Sprite(res.Child_1_of_Child_1_png);
Child_1_of_Child_1.setPosition(150,150);
Child_1.addChild(Child_1_of_Child_1);
var Child_2 = new cc.Sprite(res.Child_2_png);
Child_2.setPosition(300,300);
this.addChild(Child_2);
//don't work
if(cc.rectIntersectsRect(Child_1_of_Child_1, Child_2)){
cc.log("collided");
}
var newPosc1c1 = Child_1_of_Child_1.getParent().convertToWorldSpace(Child_1_of_Child_1.getBoundingBox());
var newPosc2 = Child_2.getParent().convertToNodeSpace(???);
//???
if(cc.rectIntersectsRect(newPosc1c1, newPosc2)){
cc.log("collided");
}
Thanks for the help
convertToWorldSpace gives you a position and cc.rectIntersectsRect requires a rect, e.g. a bounding box. Also, both bounding boxes need to have their position in world space. You would do this by taking their bounding boxes and changing the position part of the bounding boxes to world space. You won’t have to do this with Child_2, as it is basically in world space already, provided the root hasn’t moved from position (0, 0).
Try:
var worldSpaceBox = Child_1_of_Child_1.getBoundingBox();
var worldSpacePos = Child_1_of_Child_1.getParent().convertToWorldSpace(worldSpaceBox);
worldSpaceBox.x = worldSpacePos.x;
worldSpaceBox.y = worldSpacePos.y;
if (cc.rectIntersectsRect(worldSpaceBox, Child_2.getBoundingBox())) {
cc.log("collided");
}
Can’t test this at the moment, but I think it should work.You might have do the same “worldSpaceBox” code for Child_2 instead of just using its bounding box, but if the root hasn’t moved, I don’t think you will have to.
Works like a charm, I spend two days in this
and you got me the solution in 10 minutes
thanks for you time @grimfate