Add physics to sprites called from Cocostudio?

I used several sprites to create a level with cocostudio. I cloned the sprite in the scene, also call with the same name. Now I call the sprites from the code to add physical but my problem is that the physical only adds to the first cloned sprite but the others not.

As I do so that all cloned sprites have physics without having to call one by one.

example:

A ground called “Ground” in the cocostudio, now this ground is cloned many times throughout the scene but when you add physical from the code only the first sprite called “Ground” is added the physical and the others not.

I call the sprite:

Sprite *ground = (Sprite *)rootNode->getChildByName(“Ground”);

and so I add the physical:

auto groundBody = PhysicsBody::createBox(ground->getContentSize());
groundBody->setCollisionBitmask(GROUND_COLLIDER);
groundBody->setContactTestBitmask(true);
groundBody->setDynamic(false);
ground->setPhysicsBody(groundBody);

and this is the result:

My understanding with node name is that they are supposed to be unique, at least in Cocos Studio. Even if they are not, Node will only return the first element with the name, therefore your cloned ground will not be returned. What you can do is to use tag instead as they function similarly to name. Instead of name, you assign your grounds with the same tag. You then iterate the children array of the parent to find the nodes with the particular tag:

Vector<Node*> mylist;
for (const auto &t : parent->getChildren())
{
	if (t->getTag() == tag)
	{
 		mylist.pushBack(t);
	}
}

Hope it helps.

1 Like

Thanks, I’ll try.