I’m putting together a project in Cocos2d-x, and I’m trying to have a sprite change its physics body with each frame of the sprite sheet.
I know that this is remarkably inefficient, but it’s more a proof-of-concept than anything at this point, and the app isn’t that intensive. The problem is that after the physics body is set during the scene’s init method, I cannot seem to reassign it. I can remove it, but not update it.
Relevant code:
bool MainScene::init()
{
//Super init
if ( !Layer::init() )
{
return false;
}
// Init physics, create physics body for dog and assign
shapeCache = PhysicsShapeCache::getInstance();
shapeCache->addShapesWithFile("corgiPhysics.plist");
shapeCache->setBodyOnSprite("corgi-2", dogSprite);
}
The above is loading a plist made in Physics Editor and assigning a specific body.
void MainScene::update(float dt)
{
Layer::update(dt);
if (dog->getDirection() == Direction::Down)
{
Animate* animation = dog->getAnimation("up");
int frame = animation->Animate::getCurrentFrameIndex();
int fileref = frame + 9;
const std::string filename = "corgi-" + std::to_string(fileref);
dogSprite->getPhysicsBody()->removeFromWorld();
shapeCache->setBodyOnSprite(filename, dogSprite);
}
if (dog->getDirection() == Direction::Up)
{
Animate* animation = dog->getAnimation("down");
int frame = animation->Animate::getCurrentFrameIndex();
int fileref = frame + 3;
const std::string filename = "corgi-" + std::to_string(fileref);
dogSprite->getPhysicsBody()->removeFromWorld();
shapeCache->setBodyOnSprite(filename, dogSprite);
}
}
The above is checking to see what the animation frame is and changing the physics body accordingly.
void Dog::moveDogUp()
{
stopAllActions();
this->getChildByName("corgiStanding")->stopAllActions();
auto moveUp = MoveBy::create(1.8f, Vec2(0, 1500));
auto moveUpEaseIn = EaseOut::create(moveUp, 1.1);
runAction(moveUpEaseIn);
this->getChildByName("corgiStanding")->runAction(RepeatForever::create(upAnimation));
}
Finally, the above is one of the animating functions used.
I’ve broken down a lot of the functions to try to find the problem. I’ve even cut out the loading of the .plist physics bodies and tried to assign a rectangle. I’ve confirmed using cout that the update function is calling the frames and building the correct names for the physics bodies in the plist file. The update function is also removing the physics body created in the scene’s init method (visually confirmed using the debug drawer). I’ve tried changing the physics body outside of the init method (by trying to assign it at the beginning of the moveDogUp method) but no dice.
Are there specific rules to when a physics body can be assigned?
