From ae5a0bc7dcebb6ececed4bb156e269daa1bad711 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 22 Jun 2016 14:08:49 -0700 Subject: [PATCH] fix: not crash when removing body after adding it the body in the world was not being "null"ed. Github issue #15932 --- cocos/physics/CCPhysicsBody.cpp | 11 +++++++--- .../Classes/PhysicsTest/PhysicsTest.cpp | 21 +++++++++++++++++++ .../Classes/PhysicsTest/PhysicsTest.h | 10 +++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 6ffe1fc02e98..2d4c0c16d6fd 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -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() @@ -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); } } diff --git a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp index 9447df166b21..19e557b68d04 100644 --- a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp +++ b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp @@ -27,6 +27,7 @@ PhysicsTests::PhysicsTests() ADD_TEST_CASE(PhysicsFixedUpdate); ADD_TEST_CASE(PhysicsTransformTest); ADD_TEST_CASE(PhysicsIssue9959); + ADD_TEST_CASE(PhysicsIssue15932); } namespace @@ -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 \ No newline at end of file diff --git a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h index 7872a7aff40b..beb46d15f769 100644 --- a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h +++ b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h @@ -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 \ No newline at end of file