Hi guys,
In cocos2d-x 3.0RC i’ve found a strange behaviour with PhysicsBody.
If i create my Sprite:
Sprite *par = Sprite::create();
par->setColor(Color3B(0.0f, 255.0f, 0.0f));
par->setPosition(Point(visibleSize.width * 0.5f,visibleSize.height * 0.5f));
par->setAnchorPoint(Point(0.5f, 0.5f));
par->setTextureRect(cocos2d::Rect(0, 0, 600, 80));
//add child here
MoveBy *animation = MoveBy::create(4.0f, Point(0, -300));
par->runAction(animation);
this->addChild(par);
It works like a charm.
But if i add a child with a PhysicsBody attached, this child simply doesn’t move (but the parent yes).
//A method that return a sprite
Sprite *obstacle = ObstaclesMaker::obstacle(Point(300, 0), Size(300,50));
Size size = obstacle->getBoundingBox().size;
PhysicsBody *obstacleBody = PhysicsBody::createBox(size);
obstacleBody->setDynamic(false);
obstacleBody->setRotationEnable(false);
obstacleBody->setGravityEnable(false);
obstacleBody->setPositionOffset(Vect::ANCHOR_MIDDLE);
obstacleBody->setCategoryBitmask(MainGameColliderTypeWay);
//obstacleBody->setContactTestBitmask(MainGameColliderTypePlayer);
obstacle->setPhysicsBody(obstacleBody);
par->addChild(obstacle);
How to add a child with PhysicsBody and move only the parent?
Gravity and dynamics are disabled, it would work like a trigger.
Thanks
I’ve found PhysicsSprite but it doesn’t works and my app crash!
cocos2d::extension::PhysicsSprite *obstacle = cocos2d::extension::PhysicsSprite::create();
obstacle->setColor(Color3B(255.0f, 255.0f, 0.0f));
//obstacle->setPosition(Point(0, 0));
obstacle->setAnchorPoint(Point(0.5f, 0.5f));
obstacle->setTextureRect(cocos2d::Rect(0, 0, 300, 40));
Please, help me!
I’ve found a solution!
In PhysicsBody class i’ve edited the “update” function:
void PhysicsBody::update(float delta)
{
if (_node != nullptr)
{
#warning edited according to https://github.com/cocos2d/cocos2d-x/pull/5593/files
Node* parent = _node->getParent();
Point position = parent != nullptr ? parent->convertToNodeSpace(_node->getPosition()) : _node->getPosition();
_positionResetTag = false;
_rotationResetTag = true;
if (parent != nullptr && !isDynamic()) {
Point bodyPos = parent->convertToWorldSpace(_node->getPosition());
setPosition(bodyPos + _positionOffset);
}else{
_node->setPosition(position);
}
_node->setRotation(getRotation());
_positionResetTag = false;
_rotationResetTag = false;
// damping compute
if (_isDamping && _dynamic && !isResting())
{
_info->getBody()->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f);
_info->getBody()->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f);
_info->getBody()->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f);
}
}
}
Now if you add a Sprite with a PhysicsBody as a child of a Sprite with a PhysicsBody, the child follow the parent as expected during animation.