Skip to content

Commit

Permalink
fix: not crash when removing body after adding it
Browse files Browse the repository at this point in the history
the body in the world was not being "null"ed.

Github issue cocos2d#15932
  • Loading branch information
ricardoquesada committed Jun 22, 2016
1 parent edafe72 commit ae5a0bc
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
11 changes: 8 additions & 3 deletions cocos/physics/CCPhysicsBody.cpp
Expand Up @@ -953,7 +953,11 @@ void PhysicsBody::onAdd()

void PhysicsBody::onRemove()
{
CCASSERT(_owner != nullptr, "_owner can't be nullptr");

removeFromPhysicsWorld();

_owner->_physicsBody = nullptr;
}

void PhysicsBody::addToPhysicsWorld()
Expand All @@ -968,10 +972,11 @@ void PhysicsBody::addToPhysicsWorld()

void PhysicsBody::removeFromPhysicsWorld()
{
if (_world)
if (_owner)
{
_world->removeBody(this);
_world = nullptr;
auto scene = _owner->getScene();
if (scene)
scene->getPhysicsWorld()->removeBody(this);
}
}

Expand Down
21 changes: 21 additions & 0 deletions tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp
Expand Up @@ -27,6 +27,7 @@ PhysicsTests::PhysicsTests()
ADD_TEST_CASE(PhysicsFixedUpdate);
ADD_TEST_CASE(PhysicsTransformTest);
ADD_TEST_CASE(PhysicsIssue9959);
ADD_TEST_CASE(PhysicsIssue15932);
}

namespace
Expand Down Expand Up @@ -1866,4 +1867,24 @@ std::string PhysicsIssue9959::subtitle() const
return "Test Scale9Sprite run scale/move/rotation action in physics scene";
}

//
void PhysicsIssue15932::onEnter()
{
PhysicsDemo::onEnter();

PhysicsBody *pb=PhysicsBody::createBox(Size(15,5),PhysicsMaterial(0.1f,0.0f,1.0f));
this->addComponent(pb);
this->removeComponent(pb);
}

std::string PhysicsIssue15932::title() const
{
return "Github issue #15932";
}

std::string PhysicsIssue15932::subtitle() const
{
return "addComponent()/removeComponent() should not crash";
}

#endif
10 changes: 10 additions & 0 deletions tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h
Expand Up @@ -267,4 +267,14 @@ class PhysicsIssue9959 : public PhysicsDemo
virtual std::string subtitle() const override;
};

class PhysicsIssue15932 : public PhysicsDemo
{
public:
CREATE_FUNC(PhysicsIssue15932);

void onEnter() override;
virtual std::string title() const override;
virtual std::string subtitle() const override;
};

#endif // #if CC_USE_PHYSICS

0 comments on commit ae5a0bc

Please sign in to comment.