diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj b/build/cocos2d_libs.xcodeproj/project.pbxproj index 5014ec6da6..52176d9ea4 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj @@ -1884,14 +1884,6 @@ A045F6DD1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6DA1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp */; }; A045F6DE1BA816A1005076C7 /* CCCameraBackgroundBrush.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6DB1BA816A1005076C7 /* CCCameraBackgroundBrush.h */; }; A045F6DF1BA816A1005076C7 /* CCCameraBackgroundBrush.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6DB1BA816A1005076C7 /* CCCameraBackgroundBrush.h */; }; - A045F6E41BA8170A005076C7 /* CCComponentPhysics2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6E01BA8170A005076C7 /* CCComponentPhysics2d.cpp */; }; - A045F6E51BA8170A005076C7 /* CCComponentPhysics2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6E01BA8170A005076C7 /* CCComponentPhysics2d.cpp */; }; - A045F6E61BA8170A005076C7 /* CCComponentPhysics2d.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6E11BA8170A005076C7 /* CCComponentPhysics2d.h */; }; - A045F6E71BA8170A005076C7 /* CCComponentPhysics2d.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6E11BA8170A005076C7 /* CCComponentPhysics2d.h */; }; - A045F6E81BA8170A005076C7 /* CCPhysicsManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6E21BA8170A005076C7 /* CCPhysicsManager.cpp */; }; - A045F6E91BA8170A005076C7 /* CCPhysicsManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6E21BA8170A005076C7 /* CCPhysicsManager.cpp */; }; - A045F6EA1BA8170A005076C7 /* CCPhysicsManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6E31BA8170A005076C7 /* CCPhysicsManager.h */; }; - A045F6EB1BA8170A005076C7 /* CCPhysicsManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6E31BA8170A005076C7 /* CCPhysicsManager.h */; }; A045F6EF1BA81821005076C7 /* GameNode3DReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6ED1BA81821005076C7 /* GameNode3DReader.cpp */; }; A045F6F01BA81821005076C7 /* GameNode3DReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6ED1BA81821005076C7 /* GameNode3DReader.cpp */; }; A045F6F11BA81821005076C7 /* GameNode3DReader.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6EE1BA81821005076C7 /* GameNode3DReader.h */; }; @@ -4699,10 +4691,6 @@ A045F6D51BA81577005076C7 /* CCTextureCube.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureCube.h; sourceTree = ""; }; A045F6DA1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCCameraBackgroundBrush.cpp; sourceTree = ""; }; A045F6DB1BA816A1005076C7 /* CCCameraBackgroundBrush.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCCameraBackgroundBrush.h; sourceTree = ""; }; - A045F6E01BA8170A005076C7 /* CCComponentPhysics2d.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCComponentPhysics2d.cpp; sourceTree = ""; }; - A045F6E11BA8170A005076C7 /* CCComponentPhysics2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCComponentPhysics2d.h; sourceTree = ""; }; - A045F6E21BA8170A005076C7 /* CCPhysicsManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCPhysicsManager.cpp; sourceTree = ""; }; - A045F6E31BA8170A005076C7 /* CCPhysicsManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCPhysicsManager.h; sourceTree = ""; }; A045F6ED1BA81821005076C7 /* GameNode3DReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GameNode3DReader.cpp; sourceTree = ""; }; A045F6EE1BA81821005076C7 /* GameNode3DReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameNode3DReader.h; sourceTree = ""; }; A0534A631B872FFD006B03E5 /* CCDownloader-apple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCDownloader-apple.h"; sourceTree = ""; }; @@ -7428,10 +7416,6 @@ 46A170611807CE7A005B8026 /* physics */ = { isa = PBXGroup; children = ( - A045F6E01BA8170A005076C7 /* CCComponentPhysics2d.cpp */, - A045F6E11BA8170A005076C7 /* CCComponentPhysics2d.h */, - A045F6E21BA8170A005076C7 /* CCPhysicsManager.cpp */, - A045F6E31BA8170A005076C7 /* CCPhysicsManager.h */, ED74D7681A5B8A2600157FD4 /* CCPhysicsHelper.h */, 46A1706E1807CE7A005B8026 /* CCPhysicsBody.cpp */, 46A1706F1807CE7A005B8026 /* CCPhysicsBody.h */, @@ -9851,7 +9835,6 @@ 15AE1A3519AAD3D500C27E9E /* b2EdgeShape.h in Headers */, B6CAB3151AF9AA1A00B9B856 /* btBoxCollision.h in Headers */, 50643BD919BFAF4400EF68ED /* CCApplication.h in Headers */, - A045F6E61BA8170A005076C7 /* CCComponentPhysics2d.h in Headers */, B665E3581AA80A6500DDB1C5 /* CCPUOnQuotaObserverTranslator.h in Headers */, B6CAB2371AF9AA1A00B9B856 /* btCompoundCollisionAlgorithm.h in Headers */, B665E3DC1AA80A6600DDB1C5 /* CCPUScriptTranslator.h in Headers */, @@ -10023,7 +10006,6 @@ B6CAB5331AF9AA1A00B9B856 /* btTransformUtil.h in Headers */, B6DD2FEF1B04825B00E47F5F /* DetourTileCache.h in Headers */, 50ABBECD1925AB6F00A911A9 /* s3tc.h in Headers */, - A045F6EA1BA8170A005076C7 /* CCPhysicsManager.h in Headers */, B6CAB3651AF9AA1A00B9B856 /* btContinuousConvexCollision.h in Headers */, 15AE1BD119AAE01E00C27E9E /* CCControlHuePicker.h in Headers */, B5CE6DC01B3BF2B1002B0419 /* UIAbstractCheckButton.h in Headers */, @@ -10520,7 +10502,6 @@ 15AE1A9C19AAD40300C27E9E /* b2Settings.h in Headers */, 1A5701FA180BCBAD0088DEC7 /* CCMenu.h in Headers */, 15AE18BA19AAD33D00C27E9E /* CCControlButtonLoader.h in Headers */, - A045F6EB1BA8170A005076C7 /* CCPhysicsManager.h in Headers */, 1A5701FE180BCBAD0088DEC7 /* CCMenuItem.h in Headers */, 50ABC00C1926664800A911A9 /* CCDevice.h in Headers */, 1A570205180BCBD40088DEC7 /* CCClippingNode.h in Headers */, @@ -10920,7 +10901,6 @@ 15AE195A19AAD35100C27E9E /* CCProcessBase.h in Headers */, 15AE193D19AAD35100C27E9E /* CCArmatureDefine.h in Headers */, B6CAB37A1AF9AA1A00B9B856 /* btGjkEpaPenetrationDepthSolver.h in Headers */, - A045F6E71BA8170A005076C7 /* CCComponentPhysics2d.h in Headers */, B6CAB21A1AF9AA1A00B9B856 /* btBox2dBox2dCollisionAlgorithm.h in Headers */, 382384041A259005002C4610 /* CSParseBinary_generated.h in Headers */, B6CAB5401AF9AA1A00B9B856 /* cl_platform.h in Headers */, @@ -11211,7 +11191,6 @@ B665E2621AA80A6500DDB1C5 /* CCPUDoExpireEventHandler.cpp in Sources */, B665E4161AA80A6600DDB1C5 /* CCPUTextureAnimatorTranslator.cpp in Sources */, B665E41E1AA80A6600DDB1C5 /* CCPUTextureRotatorTranslator.cpp in Sources */, - A045F6E81BA8170A005076C7 /* CCPhysicsManager.cpp in Sources */, 15AE189819AAD33D00C27E9E /* CCMenuItemLoader.cpp in Sources */, 15AE1A5719AAD40300C27E9E /* b2Settings.cpp in Sources */, 50ABBE271925AB6F00A911A9 /* CCAutoreleasePool.cpp in Sources */, @@ -11518,7 +11497,6 @@ A045F6DC1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp in Sources */, B665E25A1AA80A6500DDB1C5 /* CCPUDoEnableComponentEventHandler.cpp in Sources */, A0E749F71BA8FD7F001A8332 /* UIEditBoxImpl-common.cpp in Sources */, - A045F6E41BA8170A005076C7 /* CCComponentPhysics2d.cpp in Sources */, B6DD2FB31B04825B00E47F5F /* RecastDump.cpp in Sources */, B6CAB2BB1AF9AA1A00B9B856 /* btCylinderShape.cpp in Sources */, 15AE1BD019AAE01E00C27E9E /* CCControlHuePicker.cpp in Sources */, @@ -12140,7 +12118,6 @@ B6CAB3261AF9AA1A00B9B856 /* btGImpactBvh.cpp in Sources */, 15AE18B919AAD33D00C27E9E /* CCControlButtonLoader.cpp in Sources */, B6CAB4041AF9AA1A00B9B856 /* btMultiBodyDynamicsWorld.cpp in Sources */, - A045F6E91BA8170A005076C7 /* CCPhysicsManager.cpp in Sources */, 50ABBE761925AB6F00A911A9 /* CCEventListenerTouch.cpp in Sources */, 15AE1AD219AAD40300C27E9E /* b2RopeJoint.cpp in Sources */, B29A7DCC19EE1B7700872B35 /* Skeleton.c in Sources */, @@ -12197,7 +12174,6 @@ B6CAB2521AF9AA1A00B9B856 /* btEmptyCollisionAlgorithm.cpp in Sources */, B665E2D31AA80A6500DDB1C5 /* CCPUInterParticleColliderTranslator.cpp in Sources */, B665E3331AA80A6500DDB1C5 /* CCPUOnEmissionObserver.cpp in Sources */, - A045F6E51BA8170A005076C7 /* CCComponentPhysics2d.cpp in Sources */, 1A570082180BC5A10088DEC7 /* CCActionManager.cpp in Sources */, A0534A681B872FFD006B03E5 /* CCDownloader-apple.mm in Sources */, B665E22F1AA80A6500DDB1C5 /* CCPUBoxColliderTranslator.cpp in Sources */, diff --git a/cocos/2d/CCComponent.cpp b/cocos/2d/CCComponent.cpp index 6bb111830b..53964defe3 100644 --- a/cocos/2d/CCComponent.cpp +++ b/cocos/2d/CCComponent.cpp @@ -24,10 +24,9 @@ THE SOFTWARE. #include "2d/CCComponent.h" - NS_CC_BEGIN -Component::Component(void) +Component::Component() : _owner(nullptr) , _enabled(true) { @@ -37,7 +36,7 @@ Component::Component(void) #endif } -Component::~Component(void) +Component::~Component() { } @@ -124,10 +123,11 @@ bool Component::serialize(void *ar) return true; } -Component* Component::create(void) +Component* Component::create() { Component * ret = new (std::nothrow) Component(); - if (ret != nullptr && ret->init()) + + if (ret && ret->init()) { ret->autorelease(); } @@ -135,37 +135,18 @@ Component* Component::create(void) { CC_SAFE_DELETE(ret); } + return ret; } -const std::string& Component::getName() const -{ - return _name; -} - -void Component::setName(const std::string& name) -{ - _name = name; -} - -Node* Component::getOwner() const -{ - return _owner; -} - void Component::setOwner(Node *owner) { _owner = owner; } -bool Component::isEnabled() const +void Component::setEnabled(bool enabled) { - return _enabled; -} - -void Component::setEnabled(bool b) -{ - _enabled = b; + _enabled = enabled; } NS_CC_END diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index a6151f337a..89f8d8801a 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -26,10 +26,9 @@ THE SOFTWARE. #define __CC_FRAMEWORK_COMPONENT_H__ /// @cond DO_NOT_SHOW - +#include #include "base/CCRef.h" #include "base/CCScriptSupport.h" -#include NS_CC_BEGIN @@ -45,37 +44,42 @@ enum { class CC_DLL Component : public Ref { -CC_CONSTRUCTOR_ACCESS: - /** - * @js ctor - */ - Component(void); public: + static Component* create(); + /** * @js NA * @lua NA */ - virtual ~Component(void); + virtual ~Component(); + virtual bool init(); + bool isEnabled() const { return _enabled; } + virtual void setEnabled(bool enabled); + + const std::string& getName() const { return _name; } + virtual void setName(const std::string& name) { _name = name; } + + Node* getOwner() const { return _owner; } + virtual void setOwner(Node *owner); + + virtual void update(float delta); + virtual bool serialize(void* r); + virtual void onEnter(); virtual void onExit(); virtual void onAdd(); virtual void onRemove(); - virtual void update(float delta); - virtual bool serialize(void* r); - virtual bool isEnabled() const; - virtual void setEnabled(bool b); - static Component* create(void); - - const std::string& getName() const; - void setName(const std::string& name); - - void setOwner(Node *pOwner); - Node* getOwner() const; + +CC_CONSTRUCTOR_ACCESS: + /** + * @js ctor + */ + Component(); protected: - Node *_owner; + Node* _owner; std::string _name; bool _enabled; diff --git a/cocos/2d/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp index c5801c8985..2ead55b2fd 100644 --- a/cocos/2d/CCComponentContainer.cpp +++ b/cocos/2d/CCComponentContainer.cpp @@ -58,15 +58,16 @@ bool ComponentContainer::add(Component *com) CCASSERT(com->getOwner() == nullptr, "Component already added. It can't be added again"); do { - auto typeName = typeid(*com).name(); - if (_components.find(typeName) != _components.end()) + auto componentName = com->getName(); + + if (_componentMap.find(componentName) != _componentMap.end()) { - CCASSERT(true,"ComponentContainer already have this kind of component"); + CCASSERT(true, "ComponentContainer already have this kind of component"); break; } + _componentMap[componentName] = com; + com->retain(); com->setOwner(_owner); - _components.insert(typeName, com); - _componentMap[com->getName()] = com; com->onAdd(); ret = true; @@ -74,14 +75,20 @@ bool ComponentContainer::add(Component *com) return ret; } -bool ComponentContainer::remove(const std::string& name) +bool ComponentContainer::remove(const std::string& componentName) { bool ret = false; do { - auto iter = _componentMap.find(name); - CC_BREAK_IF(iter == _componentMap.end()); - remove(iter->second); + auto iter = _componentMap.find(componentName); + CC_BREAK_IF(iter == _componentMap.end()); + + auto component = iter->second; + _componentMap.erase(componentName); + + component->onRemove(); + component->setOwner(nullptr); + component->release(); ret = true; } while(0); @@ -91,36 +98,21 @@ bool ComponentContainer::remove(const std::string& name) bool ComponentContainer::remove(Component *com) { - bool ret = false; - do - { - auto iter = _components.find(typeid(*com).name()); - if (iter != _components.end()) - { - _componentMap.erase(com->getName()); - - com->onRemove(); - com->setOwner(nullptr); - _components.erase(iter); - } - - ret = true; - } while(0); - - return ret; + return remove(com->getName()); } void ComponentContainer::removeAll() { if (!_componentMap.empty()) { - for (auto iter = _components.begin(); iter != _components.end(); ++iter) + for (auto iter = _componentMap.begin(); iter != _componentMap.end(); ++iter) { - iter->second->onRemove(); - iter->second->setOwner(nullptr); + auto component = iter->second; + component->onRemove(); + component->setOwner(nullptr); + component->release(); } - _components.clear(); _componentMap.clear(); _owner->unscheduleUpdate(); } @@ -128,11 +120,11 @@ void ComponentContainer::removeAll() void ComponentContainer::visit(float delta) { - if (!_components.empty()) + if (!_componentMap.empty()) { CC_SAFE_RETAIN(_owner); - auto iterEnd = _components.end(); - for (auto iter = _components.begin(); iter != iterEnd; ++iter) + auto iterEnd = _componentMap.end(); + for (auto iter = _componentMap.begin(); iter != iterEnd; ++iter) { iter->second->update(delta); } @@ -142,7 +134,7 @@ void ComponentContainer::visit(float delta) void ComponentContainer::onEnter() { - for (auto iter = _components.begin(); iter != _components.end(); ++iter) + for (auto iter = _componentMap.begin(); iter != _componentMap.end(); ++iter) { iter->second->onEnter(); } @@ -150,7 +142,7 @@ void ComponentContainer::onEnter() void ComponentContainer::onExit() { - for (auto iter = _components.begin(); iter != _components.end(); ++iter) + for (auto iter = _componentMap.begin(); iter != _componentMap.end(); ++iter) { iter->second->onExit(); } diff --git a/cocos/2d/CCComponentContainer.h b/cocos/2d/CCComponentContainer.h index 565ccd9210..89380f4749 100644 --- a/cocos/2d/CCComponentContainer.h +++ b/cocos/2d/CCComponentContainer.h @@ -48,38 +48,24 @@ public: * @js NA * @lua NA */ - virtual ~ComponentContainer(); - - template - T* getComponent() const - { - auto typeName = typeid(T).name(); - auto iter = _components.find(typeName); - if (iter != _components.end()) - { - return static_cast(iter->second); - } - - return nullptr; - } + ~ComponentContainer(); /** * @js getComponent */ - virtual Component* get(const std::string& name) const; - virtual bool add(Component *com); - virtual bool remove(const std::string& name); - virtual bool remove(Component *com); - virtual void removeAll(); - virtual void visit(float delta); + Component* get(const std::string& name) const; + + bool add(Component *com); + bool remove(const std::string& name); + bool remove(Component *com); + void removeAll(); + void visit(float delta); - virtual void onEnter(); - virtual void onExit(); - - bool isEmpty() const { return _componentMap.empty(); } + void onEnter(); + void onExit(); + bool isEmpty() const { return _componentMap.empty(); } private: - Map _components; std::unordered_map _componentMap; Node *_owner; diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 161713d5c5..fb1589c7a6 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -69,7 +69,7 @@ int Node::s_globalOrderOfArrival = 1; // MARK: Constructor, Destructor, Init -Node::Node(void) +Node::Node() : _rotationX(0.0f) , _rotationY(0.0f) , _rotationZ_X(0.0f) @@ -118,6 +118,9 @@ Node::Node(void) , _cascadeColorEnabled(false) , _cascadeOpacityEnabled(false) , _cameraMask(1) +#if CC_USE_PHYSICS +, _physicsBody(nullptr) +#endif { // set default scheduler and actionManager _director = Director::getInstance(); diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 6ada12dd1d..9dbdef4f07 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -56,6 +56,7 @@ class GLProgram; class GLProgramState; class Material; class Camera; +class PhysicsBody; /** * @addtogroup _2d @@ -1641,22 +1642,6 @@ public: * @return The Component by name. */ Component* getComponent(const std::string& name); - - /** - * Get a component by the type T. - * @lua NA - * @js NA - * - * @return The component that match the type T. - */ - template - T* getComponent() const - { - if (_componentContainer) - return _componentContainer->getComponent(); - else - return nullptr; - } /** * Adds a component. @@ -1862,6 +1847,19 @@ protected: std::function _onEnterTransitionDidFinishCallback; std::function _onExitTransitionDidStartCallback; +//Physics:remaining backwardly compatible +#if CC_USE_PHYSICS + PhysicsBody* _physicsBody; +public: + void setPhysicsBody(Component* physicsBody) + { + addComponent(physicsBody); + } + PhysicsBody* getPhysicsBody() const { return _physicsBody; } + + friend class PhysicsBody; +#endif + private: CC_DISALLOW_COPY_AND_ASSIGN(Node); }; diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index a2dee0aa9f..1a92a1cc05 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -35,7 +35,7 @@ THE SOFTWARE. #include "deprecated/CCString.h" #if CC_USE_PHYSICS -#include "physics/CCPhysicsManager.h" +#include "physics/CCPhysicsWorld.h" #endif #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION @@ -60,7 +60,7 @@ Scene::Scene() _navMeshDebugCamera = nullptr; #endif #if CC_USE_PHYSICS - _physicsManager = nullptr; + _physicsWorld = nullptr; #endif _ignoreAnchorPointForPosition = true; setAnchorPoint(Vec2(0.5f, 0.5f)); @@ -90,7 +90,7 @@ Scene::~Scene() CC_SAFE_RELEASE(_event); #if CC_USE_PHYSICS - delete _physicsManager; + delete _physicsWorld; #endif } @@ -279,8 +279,9 @@ Scene* Scene::createWithPhysics() bool Scene::initWithPhysics() { - _physicsManager = new (std::nothrow) PhysicsManager(this); - _physicsWorld = _physicsManager->getPhysicsWorld(); +#if CC_USE_PHYSICS + _physicsWorld = PhysicsWorld::construct(this); +#endif bool ret = false; do @@ -308,8 +309,8 @@ bool Scene::initWithPhysics() void Scene::stepPhysicsAndNavigation(float deltaTime) { #if CC_USE_PHYSICS - if (_physicsManager) - _physicsManager->update(deltaTime); + if (_physicsWorld && _physicsWorld->isAutoStep()) + _physicsWorld->update(deltaTime); #endif #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 6047977074..7ff478c835 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -40,7 +40,6 @@ class EventListenerCustom; class EventCustom; #if CC_USE_PHYSICS class PhysicsWorld; -class PhysicsManager; #endif #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION class Physics3DWorld; @@ -153,14 +152,6 @@ public: * @js NA */ inline PhysicsWorld* getPhysicsWorld() const { return _physicsWorld; } - - /** - * Get the `PhysicsManager` belongs to this `Scene`. - * - * @return PhysicsManager of the scene. - * @js NA - */ - PhysicsManager* getPhysicsManager() const { return _physicsManager; } #endif #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION @@ -190,7 +181,6 @@ protected: #if CC_USE_PHYSICS PhysicsWorld* _physicsWorld; - PhysicsManager* _physicsManager; #endif #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION diff --git a/cocos/2d/libcocos2d.vcxproj b/cocos/2d/libcocos2d.vcxproj index d07599135b..09a41229b4 100644 --- a/cocos/2d/libcocos2d.vcxproj +++ b/cocos/2d/libcocos2d.vcxproj @@ -588,11 +588,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.* - - @@ -693,7 +691,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.* - @@ -1200,12 +1197,10 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.* - - @@ -1325,7 +1320,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.* - diff --git a/cocos/2d/libcocos2d.vcxproj.filters b/cocos/2d/libcocos2d.vcxproj.filters index 3a2021637e..d52a2e3d6f 100644 --- a/cocos/2d/libcocos2d.vcxproj.filters +++ b/cocos/2d/libcocos2d.vcxproj.filters @@ -285,9 +285,6 @@ - - physics - physics @@ -297,9 +294,6 @@ physics - - physics - physics @@ -400,9 +394,6 @@ 2d - - 2d - 2d @@ -1945,9 +1936,6 @@ - - physics - physics @@ -1957,9 +1945,6 @@ physics - - physics - physics @@ -2105,9 +2090,6 @@ 2d - - 2d - 2d diff --git a/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems b/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems index 9acbdb5b28..eb4ce9b0bb 100644 --- a/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems +++ b/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems @@ -469,12 +469,10 @@ - - @@ -1075,11 +1073,9 @@ - - diff --git a/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems.filters b/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems.filters index cb369136fc..8dab9622e8 100644 --- a/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems.filters +++ b/cocos/2d/libcocos2d_8_1/libcocos2d_8_1/libcocos2d_8_1.Shared/libcocos2d_8_1.Shared.vcxitems.filters @@ -213,12 +213,6 @@ physics - - physics - - - physics - cocostudio @@ -2066,12 +2060,6 @@ physics - - physics - - - physics - cocostudio\action diff --git a/cocos/Android.mk b/cocos/Android.mk index 608ed82758..c8bbba2b0e 100644 --- a/cocos/Android.mk +++ b/cocos/Android.mk @@ -200,8 +200,6 @@ physics/CCPhysicsContact.cpp \ physics/CCPhysicsJoint.cpp \ physics/CCPhysicsShape.cpp \ physics/CCPhysicsWorld.cpp \ -physics/CCComponentPhysics2d.cpp \ -physics/CCPhysicsManager.cpp \ physics3d/CCPhysics3D.cpp \ physics3d/CCPhysics3DWorld.cpp \ physics3d/CCPhysics3DComponent.cpp \ diff --git a/cocos/cocos2d.h b/cocos/cocos2d.h index 73aa40a2b6..282321f4fb 100644 --- a/cocos/cocos2d.h +++ b/cocos/cocos2d.h @@ -186,8 +186,6 @@ THE SOFTWARE. #include "physics/CCPhysicsJoint.h" #include "physics/CCPhysicsShape.h" #include "physics/CCPhysicsWorld.h" -#include "physics/CCComponentPhysics2d.h" -#include "physics/CCPhysicsManager.h" // platform #include "platform/CCCommon.h" diff --git a/cocos/editor-support/cocostudio/CCComAttribute.cpp b/cocos/editor-support/cocostudio/CCComAttribute.cpp index e7ccc30184..11a410662a 100644 --- a/cocos/editor-support/cocostudio/CCComAttribute.cpp +++ b/cocos/editor-support/cocostudio/CCComAttribute.cpp @@ -30,12 +30,15 @@ using namespace cocos2d; namespace cocostudio { IMPLEMENT_CLASS_COMPONENT_INFO(ComAttribute) -ComAttribute::ComAttribute(void) + +const std::string ComAttribute::COMPONENT_NAME = "CCComAttribute"; + +ComAttribute::ComAttribute() { - _name = "CCComAttribute"; + _name = COMPONENT_NAME; } -ComAttribute::~ComAttribute(void) +ComAttribute::~ComAttribute() { _dict.clear(); } @@ -128,7 +131,7 @@ std::string ComAttribute::getString(const std::string& key, const std::string& d return DICTOOL->getStringValue_json(_doc, key.c_str()); } -ComAttribute* ComAttribute::create(void) +ComAttribute* ComAttribute::create() { ComAttribute * pRet = new (std::nothrow) ComAttribute(); if (pRet && pRet->init()) diff --git a/cocos/editor-support/cocostudio/CCComAttribute.h b/cocos/editor-support/cocostudio/CCComAttribute.h index 0370af0d8d..48fc113fa8 100644 --- a/cocos/editor-support/cocostudio/CCComAttribute.h +++ b/cocos/editor-support/cocostudio/CCComAttribute.h @@ -47,6 +47,8 @@ public: virtual ~ComAttribute(void); public: + const static std::string COMPONENT_NAME; + static ComAttribute* create(void); virtual bool init() override; virtual bool serialize(void* r) override; diff --git a/cocos/editor-support/cocostudio/CCComAudio.cpp b/cocos/editor-support/cocostudio/CCComAudio.cpp index 8e53f5eb88..117991e4fc 100644 --- a/cocos/editor-support/cocostudio/CCComAudio.cpp +++ b/cocos/editor-support/cocostudio/CCComAudio.cpp @@ -29,14 +29,17 @@ THE SOFTWARE. namespace cocostudio { IMPLEMENT_CLASS_COMPONENT_INFO(ComAudio) -ComAudio::ComAudio(void) + +const std::string ComAudio::COMPONENT_NAME = "CCComAudio"; + +ComAudio::ComAudio() : _filePath("") , _loop(false) { - _name = "CCComAudio"; + _name = COMPONENT_NAME; } -ComAudio::~ComAudio(void) +ComAudio::~ComAudio() { } @@ -66,17 +69,6 @@ void ComAudio::onRemove() stopAllEffects(); } -bool ComAudio::isEnabled() const -{ - return _enabled; -} - -void ComAudio::setEnabled(bool b) -{ - _enabled = b; -} - - bool ComAudio::serialize(void* r) { bool ret = false; @@ -142,7 +134,7 @@ bool ComAudio::serialize(void* r) setLoop(loop); playBackgroundMusic(filePath.c_str(), loop); } - else if(strcmp(className, "CCComAudio") == 0) + else if(strcmp(className, COMPONENT_NAME.c_str()) == 0) { preloadEffect(filePath.c_str()); } @@ -155,7 +147,7 @@ bool ComAudio::serialize(void* r) return ret; } -ComAudio* ComAudio::create(void) +ComAudio* ComAudio::create() { ComAudio * pRet = new (std::nothrow) ComAudio(); if (pRet && pRet->init()) diff --git a/cocos/editor-support/cocostudio/CCComAudio.h b/cocos/editor-support/cocostudio/CCComAudio.h index 116fe4e71f..4bbd190780 100644 --- a/cocos/editor-support/cocostudio/CCComAudio.h +++ b/cocos/editor-support/cocostudio/CCComAudio.h @@ -33,21 +33,23 @@ namespace cocostudio { class CC_STUDIO_DLL ComAudio : public cocos2d::Component { - DECLARE_CLASS_COMPONENT_INFO - public: + const static std::string COMPONENT_NAME; + /** * @js ctor */ - ComAudio(void); + ComAudio(); /** * @js NA * @lua NA */ - virtual ~ComAudio(void); + virtual ~ComAudio(); public: + static ComAudio* create(); + virtual bool init() override; /** * @js NA @@ -69,12 +71,8 @@ public: * @lua NA */ virtual void onRemove() override; - virtual bool isEnabled() const override; - virtual void setEnabled(bool b) override; - virtual bool serialize(void* r) override; - static ComAudio* create(void); - + virtual bool serialize(void* r) override; public: void end(); void preloadBackgroundMusic(const char* pszFilePath); diff --git a/cocos/editor-support/cocostudio/CCComController.cpp b/cocos/editor-support/cocostudio/CCComController.cpp index f24b7bebf5..ec351738b9 100644 --- a/cocos/editor-support/cocostudio/CCComController.cpp +++ b/cocos/editor-support/cocostudio/CCComController.cpp @@ -28,12 +28,15 @@ THE SOFTWARE. namespace cocostudio { IMPLEMENT_CLASS_COMPONENT_INFO(ComController) -ComController::ComController(void) + +const std::string ComController::COMPONENT_NAME = "CCComController"; + +ComController::ComController() { - _name = "CCComController"; + _name = COMPONENT_NAME; } -ComController::~ComController(void) +ComController::~ComController() { } @@ -70,17 +73,7 @@ void ComController::update(float delta) { } -bool ComController::isEnabled() const -{ - return _enabled; -} - -void ComController::setEnabled(bool b) -{ - _enabled = b; -} - -ComController* ComController::create(void) +ComController* ComController::create() { ComController * pRet = new (std::nothrow) ComController(); if (pRet && pRet->init()) diff --git a/cocos/editor-support/cocostudio/CCComController.h b/cocos/editor-support/cocostudio/CCComController.h index 82742a74a3..2c92345f93 100644 --- a/cocos/editor-support/cocostudio/CCComController.h +++ b/cocos/editor-support/cocostudio/CCComController.h @@ -34,46 +34,50 @@ namespace cocostudio { class CC_STUDIO_DLL ComController : public cocos2d::Component, public InputDelegate { - DECLARE_CLASS_COMPONENT_INFO public: /** * @js ctor */ - ComController(void); + ComController(); public: + const static std::string COMPONENT_NAME; + + static ComController* create(); + /** * @js NA * @lua NA */ - virtual ~ComController(void); + virtual ~ComController(); + virtual bool init() override; + /** * @js NA * @lua NA */ virtual void onEnter() override; + /** * @js NA * @lua NA */ virtual void onExit() override; + /** * @js NA * @lua NA */ virtual void onAdd() override; + /** * @js NA * @lua NA */ virtual void onRemove() override; virtual void update(float delta) override; - virtual bool isEnabled() const override; - virtual void setEnabled(bool b) override; - - static ComController* create(void); }; } diff --git a/cocos/editor-support/cocostudio/CCComExtensionData.cpp b/cocos/editor-support/cocostudio/CCComExtensionData.cpp index 1ef5d9d861..ec19e3996a 100644 --- a/cocos/editor-support/cocostudio/CCComExtensionData.cpp +++ b/cocos/editor-support/cocostudio/CCComExtensionData.cpp @@ -23,18 +23,19 @@ ****************************************************************************/ #include "CCComExtensionData.h" - #include "cocostudio/ActionTimeline/CCActionTimeline.h" - namespace cocostudio { IMPLEMENT_CLASS_COMPONENT_INFO(ComExtensionData) + + const std::string ComExtensionData::COMPONENT_NAME = "ComExtensionData"; + ComExtensionData::ComExtensionData() : _customProperty("") , _timelineData(nullptr) { - _name = "ComExtensionData"; + _name = COMPONENT_NAME; } ComExtensionData::~ComExtensionData() diff --git a/cocos/editor-support/cocostudio/CCComExtensionData.h b/cocos/editor-support/cocostudio/CCComExtensionData.h index dca3e17cd0..e4c44c3111 100644 --- a/cocos/editor-support/cocostudio/CCComExtensionData.h +++ b/cocos/editor-support/cocostudio/CCComExtensionData.h @@ -44,6 +44,8 @@ namespace cocostudio { DECLARE_CLASS_COMPONENT_INFO public: + const static std::string COMPONENT_NAME; + /** * @js NA * @lua NA diff --git a/cocos/editor-support/cocostudio/CCComRender.cpp b/cocos/editor-support/cocostudio/CCComRender.cpp index 983a9ed5aa..1676d33bcf 100644 --- a/cocos/editor-support/cocostudio/CCComRender.cpp +++ b/cocos/editor-support/cocostudio/CCComRender.cpp @@ -30,13 +30,15 @@ using namespace cocos2d; namespace cocostudio { IMPLEMENT_CLASS_COMPONENT_INFO(ComRender) -ComRender::ComRender(void) + +const std::string ComRender::COMPONENT_NAME = "CCComRender"; + +ComRender::ComRender() : _render(nullptr) { - _name = "CCComRender"; + _name = COMPONENT_NAME; } - ComRender::ComRender(cocos2d::Node *node, const char *comName) { if (node != nullptr) @@ -47,7 +49,7 @@ ComRender::ComRender(cocos2d::Node *node, const char *comName) _name.assign(comName); } -ComRender::~ComRender(void) +ComRender::~ComRender() { CC_SAFE_RELEASE_NULL(_render); } @@ -347,7 +349,7 @@ bool ComRender::serialize(void* r) return ret; } -ComRender* ComRender::create(void) +ComRender* ComRender::create() { ComRender * ret = new (std::nothrow) ComRender(); if (ret != nullptr && ret->init()) diff --git a/cocos/editor-support/cocostudio/CCComRender.h b/cocos/editor-support/cocostudio/CCComRender.h index 9abf5d7d77..1e1a048391 100644 --- a/cocos/editor-support/cocostudio/CCComRender.h +++ b/cocos/editor-support/cocostudio/CCComRender.h @@ -34,19 +34,13 @@ namespace cocostudio { class CC_STUDIO_DLL ComRender : public cocos2d::Component { DECLARE_CLASS_COMPONENT_INFO -CC_CONSTRUCTOR_ACCESS: - /** - * @js ctor - */ - ComRender(void); - ComRender(cocos2d::Node *node, const char *comName); - /** - * @js NA - * @lua NA - */ - virtual ~ComRender(void); - + public: + const static std::string COMPONENT_NAME; + + static ComRender* create(); + static ComRender* create(cocos2d::Node *node, const char *comName); + /** * @js NA * @lua NA @@ -71,12 +65,21 @@ public: virtual cocos2d::Node* getNode(); virtual void setNode(cocos2d::Node *node); - static ComRender* create(void); - static ComRender* create(cocos2d::Node *node, const char *comName); +CC_CONSTRUCTOR_ACCESS: + /** + * @js ctor + */ + ComRender(); + ComRender(cocos2d::Node *node, const char *comName); + /** + * @js NA + * @lua NA + */ + virtual ~ComRender(); + private: bool readJson(const std::string &fileName, rapidjson::Document &doc); -private: cocos2d::Node *_render; }; diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 7adfd5f1c2..d9137358f1 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -223,15 +223,15 @@ std::string SceneReader::getComponentClassName(const std::string &name) { comName = "ComRender"; } - else if (name == "CCComAudio" || name == "CCBackgroundAudio") + else if (name == ComAudio::COMPONENT_NAME || name == "CCBackgroundAudio") { comName = "ComAudio"; } - else if (name == "CCComController") + else if (name == ComController::COMPONENT_NAME) { comName = "ComController"; } - else if (name == "CCComAttribute") + else if (name == ComAttribute::COMPONENT_NAME) { comName = "ComAttribute"; } diff --git a/cocos/editor-support/cocostudio/WidgetReader/GameNode3DReader/GameNode3DReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/GameNode3DReader/GameNode3DReader.cpp index 29c08d2dd2..9d7ab06ecb 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/GameNode3DReader/GameNode3DReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/GameNode3DReader/GameNode3DReader.cpp @@ -414,10 +414,10 @@ namespace cocostudio std::string customProperty = options->customProperty()->c_str(); ComExtensionData* extensionData = ComExtensionData::create(); - extensionData->setCustomProperty(customProperty);\ - if (node->getComponent("ComExtensionData")) + extensionData->setCustomProperty(customProperty); + if (node->getComponent(ComExtensionData::COMPONENT_NAME)) { - node->removeComponent("ComExtensionData"); + node->removeComponent(ComExtensionData::COMPONENT_NAME); } node->addComponent(extensionData); } diff --git a/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp index 9d34dac00a..07ef8b6159 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp @@ -512,9 +512,9 @@ namespace cocostudio ComExtensionData* extensionData = ComExtensionData::create(); extensionData->setCustomProperty(customProperty); extensionData->setActionTag(actionTag); - if (node->getComponent("ComExtensionData")) + if (node->getComponent(ComExtensionData::COMPONENT_NAME)) { - node->removeComponent("ComExtensionData"); + node->removeComponent(ComExtensionData::COMPONENT_NAME); } node->addComponent(extensionData); diff --git a/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp index 37e8693031..c11487970c 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp @@ -808,9 +808,9 @@ namespace cocostudio ComExtensionData* extensionData = ComExtensionData::create(); extensionData->setCustomProperty(customProperty); extensionData->setActionTag(actionTag); - if (node->getComponent("ComExtensionData")) + if (node->getComponent(ComExtensionData::COMPONENT_NAME)) { - node->removeComponent(extensionData); + node->removeComponent(ComExtensionData::COMPONENT_NAME); } node->addComponent(extensionData); diff --git a/cocos/physics/CCComponentPhysics2d.cpp b/cocos/physics/CCComponentPhysics2d.cpp deleted file mode 100644 index 08c4c9c3b8..0000000000 --- a/cocos/physics/CCComponentPhysics2d.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "base/ccConfig.h" // to include defination of CC_USE_PHYSICS -#if CC_USE_PHYSICS - -#include "physics/CCComponentPhysics2d.h" -#include "physics/CCPhysicsBody.h" -#include "physics/CCPhysicsManager.h" -#include "2d/CCNode.h" -#include "base/CCDirector.h" - -NS_CC_BEGIN - -const std::string ComponentPhysics2d::COMPONENT_NAME = "physics2d"; - -ComponentPhysics2d* ComponentPhysics2d::create() -{ - return create(nullptr); -} - -ComponentPhysics2d* ComponentPhysics2d::create(PhysicsBody *physicsBody) -{ - auto ret = new (std::nothrow) ComponentPhysics2d(physicsBody); - if (ret) - ret->autorelease(); - - return ret; -} - -ComponentPhysics2d::ComponentPhysics2d() -: _physicsBody(nullptr) -, _physicsRotation(0.0f) -, _ownerOriginRotation(0.0f) -{ - _name = COMPONENT_NAME; -} - -ComponentPhysics2d::ComponentPhysics2d(PhysicsBody* physicsBody) -: _physicsRotation(0.0f) -, _ownerOriginRotation(0.0f) -, _physicsBody(nullptr) // should set to null to invoke setPhysicsBody() -{ - _name = COMPONENT_NAME; - setPhysicsBody(physicsBody); -} - -ComponentPhysics2d::~ComponentPhysics2d() -{ - removePhysicsBody(); -} - -// true if two Vec3 equals, false else -bool ComponentPhysics2d::isVec3Equal(const cocos2d::Vec3 &v1, const cocos2d::Vec3 &v2) const -{ - return fabs(v1.x - v2.x) < FLT_EPSILON && - fabs(v1.x - v2.y) < FLT_EPSILON; -} - -void ComponentPhysics2d::beforeSimulation() -{ - if (nullptr == _physicsBody) - return; - - _nodeToWorldTransform = _owner->getNodeToWorldTransform(); - - // set scale - _nodeToWorldTransform.getScale(&_scale); - if (! isVec3Equal(_scale, _recordScale)) - { - _physicsBody->setScale(_scale.x, _scale.y); - _recordScale = _scale; - } - - // set rotation - if (_owner->getParent()) - { - _physicsRotation = getPhysicsRotation(_owner->getParent()) + _owner->getRotation(); - } - _physicsBody->setRotation(_physicsRotation - _ownerOriginRotation); - - // set position - auto worldPosition = _ownerCenterOffset; - _nodeToWorldTransform.transformPoint(&worldPosition); - _physicsBody->setPosition(Vec2(worldPosition.x, worldPosition.y)); - - getParentToWorldTransform().getInversed().transformPoint(&worldPosition); - _offset.x = worldPosition.x - _owner->getPosition().x; - _offset.y = worldPosition.y - _owner->getPosition().y; -} - -void ComponentPhysics2d::afterSimulation() -{ - if (nullptr == _physicsBody) - return; - - // set Node position - auto worldPosition = _physicsBody->getPosition(); - Vec3 positionInParent(worldPosition.x, worldPosition.y, 0); - getParentToWorldTransform().getInversed().transformPoint(&positionInParent); - _owner->setPosition(positionInParent.x - _offset.x, positionInParent.y - _offset.y); - - // set Node rotation - _physicsRotation = _physicsBody->getRotation(); - _owner->setRotation(_physicsRotation - getPhysicsRotation(_owner->getParent()) + _ownerOriginRotation); -} - -void ComponentPhysics2d::setPhysicsBody(PhysicsBody *physicsBody) -{ - removeFromPhysicsManager(); - - if (physicsBody != _physicsBody) - { - if (nullptr != _physicsBody) - { - _physicsBody->release(); - _physicsBody->_componentBelongsTo = nullptr; - } - - // two components should not share the same physics body - if (physicsBody && physicsBody->_componentBelongsTo != nullptr) - physicsBody->_componentBelongsTo->_physicsBody = nullptr; - - _physicsBody = physicsBody; - - if (nullptr != _physicsBody) - { - _physicsBody->retain(); - _physicsBody->_componentBelongsTo = this; - } - } - - addToPhysicsManager(); -} - -PhysicsBody* ComponentPhysics2d::getPhysicsBody() const -{ - return _physicsBody; -} - -void ComponentPhysics2d::setEnabled(bool value) -{ - Component::setEnabled(value); - - if (value) - addToPhysicsManager(); - else - removeFromPhysicsManager(); -} - -void ComponentPhysics2d::onEnter() -{ - addToPhysicsManager(); -} - -void ComponentPhysics2d::onExit() -{ - removeFromPhysicsManager(); -} - -void ComponentPhysics2d::onAdd() -{ - auto contentSize = _owner->getContentSize(); - _ownerCenterOffset.x = 0.5 * contentSize.width; - _ownerCenterOffset.y = 0.5 * contentSize.height; - - _ownerOriginRotation = _owner->getRotation(); - - // component may be added after onEnter() has been invoked, so we should add - // this line to make sure physics body is added to physics world - addToPhysicsManager(); -} - -void ComponentPhysics2d::onRemove() -{ - removePhysicsBody(); -} - -void ComponentPhysics2d::removePhysicsBody() -{ - removeFromPhysicsManager(); - - if (_physicsBody) - { - _physicsBody->_componentBelongsTo = nullptr; - _physicsBody->release(); - _physicsBody = nullptr; - } -} - -void ComponentPhysics2d::addToPhysicsManager() -{ - if (_owner) - { - auto scene = _owner->getScene(); - if (scene) - scene->getPhysicsManager()->addPhysicsComponent(this); - } - -} - -void ComponentPhysics2d::removeFromPhysicsManager() -{ - if (_owner) - { - auto scene = _owner->getScene(); - if (scene) - scene->getPhysicsManager()->removePhysicsComponent(this); - } -} - -Mat4 ComponentPhysics2d::getParentToWorldTransform() const -{ - if (_owner->getParent()) - return _owner->getParent()->getNodeToWorldTransform(); - else - return _owner->getNodeToWorldTransform(); -} - -float ComponentPhysics2d::getPhysicsRotation(Node *node) const -{ - if (!node) - return 0.0f; - - auto physicsComponent = node->getComponent(); - if (physicsComponent) - { - return physicsComponent->_physicsRotation; - } - else - { - auto parent = node->getParent(); - if (parent) - return getPhysicsRotation(parent) + node->getRotation(); - else - return 0.0f; - } -} - -NS_CC_END - -#endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCComponentPhysics2d.h b/cocos/physics/CCComponentPhysics2d.h deleted file mode 100644 index 6814b883ef..0000000000 --- a/cocos/physics/CCComponentPhysics2d.h +++ /dev/null @@ -1,140 +0,0 @@ -/**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#pragma once - -#include "base/ccConfig.h" // to include defination of CC_USE_PHYSICS -#if CC_USE_PHYSICS - -#include "platform/CCPlatformMacros.h" -#include "2d/CCComponent.h" - -NS_CC_BEGIN - -/** - * @addtogroup physics - * @{ - * @addtogroup physics_2d - * @{ - */ - -class PhysicsBody; - -class CC_DLL ComponentPhysics2d : public Component -{ -public: - /** - * Create a physics component without physics body. Can set phyiscs body later with setPhysicsBody(). - * I am not sure if we need this function, because i think physics body is needed when creating a - * physics component. But i think it is needed by editor, so i keep this function. - * - * @return A pointer of `ComponentPhysics2d` that is autoreleased. - */ - static ComponentPhysics2d* create(); - /** - * Create a physics component with physics body. - * - * @param physicsBody The physics body that belongs to this component. - * @return A pointer of `ComponentPhysics2d` that is autoreleased. - */ - static ComponentPhysics2d* create(PhysicsBody *physicsBody); - - virtual ~ComponentPhysics2d(); - - /// @cond DO_NOT_SHOW - - /** - * Synchronize Node's status(position, rotation, scale) to phyiscs body. - * It is invoked before physics simulation. - * - * @warning Don't invoke this funciton by yourself. - */ - void beforeSimulation(); - /** - * Synchronize physics body's status(position, rotation) to phyiscs body. - * It is invoked after physics simulation. - * - * @warning Don't invoke this funciton by yourself. - */ - void afterSimulation(); - - /// @endcond DO_NOT_SHOW - - /** - * Set physics body of this physics component. If the physics body is set to - * another physics component before, will set another physics component's physics - * body to null. - * - * @param physicsBody The physics body belongs to this component. - */ - void setPhysicsBody(PhysicsBody *physicsBody); - /** - * Get the physics body of this component. - * - * @return The physics body of this component. - */ - PhysicsBody* getPhysicsBody() const; - - virtual void setEnabled(bool value) override; - virtual void onEnter() override; - virtual void onExit() override; - virtual void onAdd() override; - virtual void onRemove() override; - -public: - const static std::string COMPONENT_NAME; - -CC_CONSTRUCTOR_ACCESS: - ComponentPhysics2d(); - ComponentPhysics2d(PhysicsBody *phsicsBody); - -private: - void removePhysicsBody(); - void addToPhysicsManager(); - void removeFromPhysicsManager(); - Mat4 getParentToWorldTransform() const; - float getPhysicsRotation(Node *node) const; - bool isVec3Equal(const Vec3 &v1, const Vec3 &v2) const; - -private: - // this physic body of this component - PhysicsBody *_physicsBody; - // offset between owner's center point and down left point - Vec3 _ownerCenterOffset; - Mat4 _nodeToWorldTransform; - // offset of owner's center point and anchor point in parent coordinate - Vec2 _offset; - float _physicsRotation; - // the rotation of owner when the component is added to, the value will not change - float _ownerOriginRotation; - Vec3 _recordScale; - Vec3 _scale; -}; - -/** @} */ -/** @} */ - -NS_CC_END - -#endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 563bb9973f..d9d30e1e50 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -35,7 +35,6 @@ #include "physics/CCPhysicsJoint.h" #include "physics/CCPhysicsWorld.h" #include "physics/CCPhysicsHelper.h" -#include "physics/CCComponentPhysics2d.h" static inline void cpBodyUpdateVelocityWithoutGravity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt) { @@ -45,6 +44,8 @@ static inline void cpBodyUpdateVelocityWithoutGravity(cpBody *body, cpVect gravi NS_CC_BEGIN extern const float PHYSICS_INFINITY; +const std::string PhysicsBody::COMPONENT_NAME = "PhysicsBody"; + namespace { static const float MASS_DEFAULT = 1.0; @@ -55,7 +56,6 @@ PhysicsBody::PhysicsBody() : _world(nullptr) , _cpBody(nullptr) , _dynamic(true) -, _enabled(true) , _rotationEnabled(true) , _gravityEnabled(true) , _massDefault(true) @@ -71,9 +71,10 @@ PhysicsBody::PhysicsBody() , _rotationOffset(0) , _recordedRotation(0.0f) , _recordedAngle(0.0) -, _componentBelongsTo(nullptr) , _massSetByUser(false) , _momentSetByUser(false) +, _recordScaleX(1.f) +, _recordScaleY(1.f) { } @@ -215,7 +216,7 @@ PhysicsBody* PhysicsBody::createEdgeBox(const Size& size, const PhysicsMaterial& } CC_SAFE_DELETE(body); - + return nullptr; } @@ -255,7 +256,7 @@ bool PhysicsBody::init() { do { - _cpBody = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); + _cpBody = cpBodyNew(_mass, _moment); CC_BREAK_IF(_cpBody == nullptr); @@ -334,11 +335,6 @@ void PhysicsBody::setGravityEnable(bool enable) } } -void PhysicsBody::setPosition(const Vec2& position) -{ - cpBodySetPos(_cpBody, PhysicsHelper::point2cpv(position + _positionOffset)); -} - void PhysicsBody::setRotation(float rotation) { _recordedRotation = rotation; @@ -366,11 +362,31 @@ void PhysicsBody::setScale(float scaleX, float scaleY) } } +void PhysicsBody::setPosition(float positionX, float positionY) +{ + cpVect tt; + + tt.x = positionX + _positionOffset.x; + tt.y = positionY + _positionOffset.y; + + cpBodySetPos(_cpBody, tt); +} + Vec2 PhysicsBody::getPosition() const { return Vec2(_cpBody->p.x - _positionOffset.x, _cpBody->p.y - _positionOffset.y); } +void PhysicsBody::setPositionOffset(const Vec2& position) +{ + if (!_positionOffset.equals(position)) + { + Vec2 pos = getPosition(); + _positionOffset = position; + setPosition(pos.x, pos.y); + } +} + float PhysicsBody::getRotation() { if (_recordedAngle != cpBodyGetAngle(_cpBody)) { @@ -409,12 +425,7 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* return shape; } -void PhysicsBody::applyForce(const Vect& force) -{ - applyForce(force, Vec2::ZERO); -} - -void PhysicsBody::applyForce(const Vect& force, const Vec2& offset) +void PhysicsBody::applyForce(const Vec2& force, const Vec2& offset) { if (_dynamic && _mass != PHYSICS_INFINITY) { @@ -427,19 +438,14 @@ void PhysicsBody::resetForces() cpBodyResetForces(_cpBody); } -void PhysicsBody::applyImpulse(const Vect& impulse) -{ - applyImpulse(impulse, Vec2()); -} - -void PhysicsBody::applyImpulse(const Vect& impulse, const Vec2& offset) +void PhysicsBody::applyImpulse(const Vec2& impulse, const Vec2& offset) { cpBodyApplyImpulse(_cpBody, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); } void PhysicsBody::applyTorque(float torque) { - cpBodySetTorque(_cpBody, PhysicsHelper::float2cpfloat(torque)); + cpBodySetTorque(_cpBody, torque); } void PhysicsBody::setMass(float mass) @@ -559,7 +565,7 @@ void PhysicsBody::addMoment(float moment) // the static body's mass and moment is always infinity if (_rotationEnabled && _dynamic) { - cpBodySetMoment(_cpBody, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_cpBody, _moment); } } @@ -597,7 +603,7 @@ void PhysicsBody::setAngularVelocity(float velocity) return; } - cpBodySetAngVel(_cpBody, PhysicsHelper::float2cpfloat(velocity)); + cpBodySetAngVel(_cpBody, velocity); } float PhysicsBody::getAngularVelocity() @@ -607,7 +613,7 @@ float PhysicsBody::getAngularVelocity() void PhysicsBody::setVelocityLimit(float limit) { - cpBodySetVelLimit(_cpBody, PhysicsHelper::float2cpfloat(limit)); + cpBodySetVelLimit(_cpBody, limit); } float PhysicsBody::getVelocityLimit() @@ -617,7 +623,7 @@ float PhysicsBody::getVelocityLimit() void PhysicsBody::setAngularVelocityLimit(float limit) { - cpBodySetAngVelLimit(_cpBody, PhysicsHelper::float2cpfloat(limit)); + cpBodySetAngVelLimit(_cpBody, limit); } float PhysicsBody::getAngularVelocityLimit() @@ -634,7 +640,7 @@ void PhysicsBody::setMoment(float moment) // the static body's mass and moment is always infinity if (_rotationEnabled && _dynamic) { - cpBodySetMoment(_cpBody, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_cpBody, _moment); } } @@ -719,21 +725,10 @@ void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/) void PhysicsBody::removeFromWorld() { - if (_world) - { - _world->removeBody(this); - } + removeFromPhysicsWorld(); } -Node* PhysicsBody::getNode() const -{ - if (_componentBelongsTo) - return _componentBelongsTo->getOwner(); - else - return nullptr; -} - -void PhysicsBody::setEnable(bool enable) +void PhysicsBody::setEnabled(bool enable) { if (_enabled != enable) { @@ -762,7 +757,8 @@ void PhysicsBody::setResting(bool rest) const if (rest && !isResting()) { cpBodySleep(_cpBody); - }else if(!rest && isResting()) + } + else if(!rest && isResting()) { cpBodyActivate(_cpBody); } @@ -859,16 +855,6 @@ int PhysicsBody::getGroup() const } } -void PhysicsBody::setPositionOffset(const Vec2& position) -{ - if (!_positionOffset.equals(position)) - { - Vec2 pos = getPosition(); - _positionOffset = position; - setPosition(pos); - } -} - void PhysicsBody::setRotationOffset(float rotation) { if (std::abs(_rotationOffset - rotation) > 0.5f) @@ -889,6 +875,100 @@ Vec2 PhysicsBody::local2World(const Vec2& point) return PhysicsHelper::cpv2point(cpBodyLocal2World(_cpBody, PhysicsHelper::point2cpv(point))); } +void PhysicsBody::beforeSimulation(const Mat4& parentToWorldTransform, const Mat4& nodeToWorldTransform, float scaleX, float scaleY, float rotation) +{ + if (_recordScaleX != scaleX || _recordScaleY != scaleY) + { + _recordScaleX = scaleX; + _recordScaleY = scaleY; + setScale(scaleX, scaleY); + } + + // set rotation + if (_recordedRotation != rotation) + { + setRotation(rotation); + } + + // set position + auto worldPosition = _ownerCenterOffset; + nodeToWorldTransform.transformVector(worldPosition.x, worldPosition.y, worldPosition.z, 1.f, &worldPosition); + setPosition(worldPosition.x, worldPosition.y); + + _recordPosX = worldPosition.x; + _recordPosY = worldPosition.y; + + if (_owner->getAnchorPoint() != Vec2::ANCHOR_MIDDLE) + { + parentToWorldTransform.getInversed().transformVector(worldPosition.x, worldPosition.y, worldPosition.z, 1.f, &worldPosition); + _offset.x = worldPosition.x - _owner->getPositionX(); + _offset.y = worldPosition.y - _owner->getPositionY(); + } +} + +void PhysicsBody::afterSimulation(const Mat4& parentToWorldTransform, float parentRotation) +{ + // set Node position + auto tmp = getPosition(); + Vec3 positionInParent(tmp.x, tmp.y, 0.f); + if (_recordPosX != positionInParent.x || _recordPosY != positionInParent.y) + { + parentToWorldTransform.getInversed().transformVector(positionInParent.x, positionInParent.y, positionInParent.z, 1.f, &positionInParent); + _owner->setPosition(positionInParent.x - _offset.x, positionInParent.y - _offset.y); + } + + // set Node rotation + _owner->setRotation(getRotation() - parentRotation); +} + +void PhysicsBody::onEnter() +{ + addToPhysicsWorld(); +} + +void PhysicsBody::onExit() +{ + removeFromPhysicsWorld(); +} + +void PhysicsBody::onAdd() +{ + _owner->_physicsBody = this; + auto contentSize = _owner->getContentSize(); + _ownerCenterOffset.x = 0.5 * contentSize.width; + _ownerCenterOffset.y = 0.5 * contentSize.height; + + setRotationOffset(_owner->getRotation()); + + // component may be added after onEnter() has been invoked, so we should add + // this line to make sure physics body is added to physics world + addToPhysicsWorld(); +} + +void PhysicsBody::onRemove() +{ + removeFromPhysicsWorld(); +} + +void PhysicsBody::addToPhysicsWorld() +{ + if (_owner) + { + auto scene = _owner->getScene(); + if (scene) + scene->getPhysicsWorld()->addBody(this); + } +} + +void PhysicsBody::removeFromPhysicsWorld() +{ + if (_world) + { + _world->removeBody(this); + _world = nullptr; + } +} + NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index ad0db3d1a5..b16722a73c 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -28,7 +28,7 @@ #include "base/ccConfig.h" #if CC_USE_PHYSICS -#include "base/CCRef.h" +#include "2d/CCComponent.h" #include "math/CCGeometry.h" #include "physics/CCPhysicsShape.h" #include "base/CCVector.h" @@ -38,14 +38,11 @@ struct cpBody; NS_CC_BEGIN class Node; -class Sprite; class PhysicsWorld; class PhysicsJoint; -class ComponentPhysics2d; typedef Vec2 Vect; - const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); /** @@ -63,45 +60,47 @@ const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); * If you create body with createEdgeXXX, the mass and moment will be PHYSICS_INFINITY by default. And it's a static body. * You can change mass and moment with setMass() and setMoment(). And you can change the body to be dynamic or static by use function setDynamic(). */ -class CC_DLL PhysicsBody : public Ref +class CC_DLL PhysicsBody : public Component { public: + const static std::string COMPONENT_NAME; + /** - Create a body with default mass and moment. - - This default mass value is 1.0. - This default moment value is 200. - @return An autoreleased PhysicsBody object pointer. + * Create a body with default mass and moment. + * + * This default mass value is 1.0. + * This default moment value is 200. + * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* create(); /** - Create a body with mass and default moment. - - @param mass This body's mass. - @return An autoreleased PhysicsBody object pointer. + * Create a body with mass and default moment. + * + * @param mass This body's mass. + * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* create(float mass); /** - Create a body with mass and moment. - - @param mass This body's mass. - @param moment This body's moment. - @return An autoreleased PhysicsBody object pointer. + * Create a body with mass and moment. + * + * @param mass This body's mass. + * @param moment This body's moment. + * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* create(float mass, float moment); - /** - Create a body contains a circle. - - @param radius A float number, it is the circle's radius. - @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. - @param offset A Vec2 object, it is the offset from the body’s center of gravity in body local coordinates. - @return An autoreleased PhysicsBody object pointer. + /** + * Create a body contains a circle. + * + * @param radius A float number, it is the circle's radius. + * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. + * @param offset A Vec2 object, it is the offset from the body’s center of gravity in body local coordinates. + * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO); - /** + /** * Create a body contains a box shape. * * @param size Size contains this box's width and height. @@ -110,7 +109,7 @@ public: * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO); - + /** * @brief Create a body contains a polygon shape. * @@ -121,10 +120,10 @@ public: * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* createPolygon(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO); - - /** - Create a body contains a EdgeSegment shape. - + + /** + * Create a body contains a EdgeSegment shape. + * * @param a It's the edge's begin position. * @param b It's the edge's end position. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. @@ -132,10 +131,9 @@ public: * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* createEdgeSegment(const Vec2& a, const Vec2& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - - /** - Create a body contains a EdgeBox shape. + /** + * Create a body contains a EdgeBox shape. * @param size Size contains this box's width and height. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param border It's a edge's border width. @@ -143,10 +141,10 @@ public: * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* createEdgeBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, const Vec2& offset = Vec2::ZERO); - - /** - Create a body contains a EdgePolygon shape. - + + /** + * Create a body contains a EdgePolygon shape. + * * @param points Points is an array of Vec2 structs defining a convex hull with a clockwise winding. * @param count An interger number, contains the count of the points array. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. @@ -154,18 +152,18 @@ public: * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* createEdgePolygon(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - - /** - Create a body contains a EdgeChain shape. - + + /** + * Create a body contains a EdgeChain shape. + * * @param points A Vec2 object pointer, it contains an array of points. * @param count An interger number, contains the count of the points array. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param border It's a edge's border width. - * @return An autoreleased PhysicsBody object pointer. + * @return An autoreleased PhysicsBody object pointer. */ static PhysicsBody* createEdgeChain(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - + /** * @brief Add a shape to body. * @param shape The shape to be added. @@ -189,90 +187,69 @@ public: void removeShape(int tag, bool reduceMassAndMoment = true); /** - Remove all shapes. - + * Remove all shapes. + * * @param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true. */ void removeAllShapes(bool reduceMassAndMoment = true); /** - Get the body shapes. - + * Get the body shapes. + * * @return A Vector object contains PhysicsShape pointer. */ inline const Vector& getShapes() const { return _shapes; } - - /** - Get the first shape of the body shapes. - - @return The first shape in this body. - */ - inline PhysicsShape* getFirstShape() const { return _shapes.size() >= 1 ? _shapes.at(0) : nullptr; } /** - get the shape of the body. - - @param tag An interger number that identifies a PhysicsShape object. - @return A PhysicsShape object pointer or nullptr if no shapes were found. + * get the shape of the body. + * + * @param tag An interger number that identifies a PhysicsShape object. + * @return A PhysicsShape object pointer or nullptr if no shapes were found. */ PhysicsShape* getShape(int tag) const; /** - Applies a continuous force to body. - - @param force The force is applies to this body. + * Applies a continuous force to body. + * + * @param force The force is applies to this body. + * @param offset A Vec2 object, it is the offset from the body’s center of gravity in world coordinates. */ - virtual void applyForce(const Vect& force); - - /** - Applies a continuous force to body. - - @param force The force is applies to this body. - @param offset A Vec2 object, it is the offset from the body’s center of gravity in world coordinates. - */ - virtual void applyForce(const Vect& force, const Vec2& offset); + virtual void applyForce(const Vec2& force, const Vec2& offset = Vec2::ZERO); /** - reset all the force applied to body. + * reset all the force applied to body. */ virtual void resetForces(); /** - Applies a immediate force to body. - - @param impulse The impulse is applies to this body. + * Applies a immediate force to body. + * + * @param impulse The impulse is applies to this body. + * @param offset A Vec2 object, it is the offset from the body’s center of gravity in world coordinates. */ - virtual void applyImpulse(const Vect& impulse); - - /** - Applies a immediate force to body. - - @param impulse The impulse is applies to this body. - @param offset A Vec2 object, it is the offset from the body’s center of gravity in world coordinates. - */ - virtual void applyImpulse(const Vect& impulse, const Vec2& offset); + virtual void applyImpulse(const Vec2& impulse, const Vec2& offset = Vec2::ZERO); /** - Applies a torque force to body. - - @param torque The torque is applies to this body. + * Applies a torque force to body. + * + * @param torque The torque is applies to this body. */ virtual void applyTorque(float torque); /** - Set the velocity of a body. - - @param velocity The velocity is set to this body. + * Set the velocity of a body. + * + * @param velocity The velocity is set to this body. */ - virtual void setVelocity(const Vect& velocity); + virtual void setVelocity(const Vec2& velocity); /** Get the velocity of a body. */ virtual Vec2 getVelocity(); /** - Set the angular velocity of a body. - - @param velocity The angular velocity is set to this body. + * Set the angular velocity of a body. + * + * @param velocity The angular velocity is set to this body. */ virtual void setAngularVelocity(float velocity); @@ -302,11 +279,12 @@ public: /** get the world body added to. */ inline PhysicsWorld* getWorld() const { return _world; } + /** get all joints the body have */ inline const std::vector& getJoints() const { return _joints; } - /** get the sprite the body set to. */ - Node* getNode() const; + /** get the node the body set to. */ + Node* getNode() const { return _owner; } /** * A mask that defines which categories this physics body belongs to. @@ -333,23 +311,23 @@ public: void setCollisionBitmask(int bitmask); /** - Return bitmask of first shape. - + * Return bitmask of first shape. + * * @return If there is no shape in body, return default value.(0xFFFFFFFF) */ int getCategoryBitmask() const; /** - Return bitmask of first shape. - + * Return bitmask of first shape. + * * @return If there is no shape in body, return default value.(0x00000000) */ int getContactTestBitmask() const; /** - Return bitmask of first shape. - - @return If there is no shape in body, return default value.(0xFFFFFFFF) + * Return bitmask of first shape. + * + * @return If there is no shape in body, return default value.(0xFFFFFFFF) */ int getCollisionBitmask() const; @@ -362,21 +340,21 @@ public: void setGroup(int group); /** - Return group of first shape. - - @return If there is no shape in body, return default value.(0) + * Return group of first shape. + * + * @return If there is no shape in body, return default value.(0) */ int getGroup() const; /** get the body position. */ Vec2 getPosition() const; - + /** get the body rotation. */ float getRotation(); - + /** set body position offset, it's the position witch relative to node */ void setPositionOffset(const Vec2& position); - + /** get body position offset. */ const Vec2& getPositionOffset() const { return _positionOffset; } @@ -408,6 +386,7 @@ public: /** Get the body mass. */ inline float getMass() const { return _mass; } + /** * @brief Add mass to body. * @@ -453,6 +432,7 @@ public: /** Get angular damping. */ inline float getAngularDamping() const { return _angularDamping; } + /** * Set angular damping. * @@ -466,20 +446,13 @@ public: /** set body to rest */ void setResting(bool rest) const; - - /** - * Whether the body is enabled. - * - * If the body it isn't enabled, it will not has simulation by world. - */ - inline bool isEnabled() const { return _enabled; } /** * Set the enable value. * * If the body it isn't enabled, it will not has simulation by world. */ - void setEnable(bool enable); + virtual void setEnabled(bool enable) override; /** Whether the body can rotation. */ inline bool isRotationEnabled() const { return _rotationEnabled; } @@ -507,33 +480,42 @@ public: /** Get the rigid body of chipmunk. */ cpBody* getCPBody() const { return _cpBody; } + + virtual void onEnter() override; + virtual void onExit() override; + virtual void onAdd() override; + virtual void onRemove() override; protected: + PhysicsBody(); + virtual ~PhysicsBody(); + + virtual bool init(); - bool init(); - - virtual void setPosition(const Vec2& position); + virtual void setPosition(float positionX, float positionY); + virtual void setRotation(float rotation); + virtual void setScale(float scaleX, float scaleY); void update(float delta); void removeJoint(PhysicsJoint* joint); + inline void updateDamping() { _isDamping = _linearDamping != 0.0f || _angularDamping != 0.0f; } - -protected: - PhysicsBody(); - virtual ~PhysicsBody(); - + + void addToPhysicsWorld(); + void removeFromPhysicsWorld(); + + void beforeSimulation(const Mat4& parentToWorldTransform, const Mat4& nodeToWorldTransform, float scaleX, float scaleY, float rotation); + void afterSimulation(const Mat4& parentToWorldTransform, float parentRotation); protected: std::vector _joints; Vector _shapes; PhysicsWorld* _world; - // weak reference - ComponentPhysics2d *_componentBelongsTo; + cpBody* _cpBody; bool _dynamic; - bool _enabled; bool _rotationEnabled; bool _gravityEnabled; bool _massDefault; @@ -545,6 +527,7 @@ protected: bool _isDamping; float _linearDamping; float _angularDamping; + int _tag; // when setMass() is invoked, it means body's mass is not calculated by shapes @@ -557,13 +540,19 @@ protected: float _recordedRotation; double _recordedAngle; + // offset between owner's center point and down left point + Vec3 _ownerCenterOffset; + // offset of owner's center point and anchor point in parent coordinate + Vec2 _offset; + float _recordScaleX; + float _recordScaleY; + + float _recordPosX; + float _recordPosY; + friend class PhysicsWorld; friend class PhysicsShape; friend class PhysicsJoint; - friend class Node; - friend class Layer; - friend class ProtectedNode; - friend class ComponentPhysics2d; }; /** @} */ diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 55833a38e9..809ead1de5 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -137,7 +137,7 @@ void PhysicsContactPreSolve::setFriction(float friction) static_cast(_contactInfo)->u = friction; } -void PhysicsContactPreSolve::setSurfaceVelocity(const Vect& velocity) +void PhysicsContactPreSolve::setSurfaceVelocity(const Vec2& velocity) { static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(velocity); } diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index cb8d76edf6..4523bf8850 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -40,8 +40,6 @@ class PhysicsShape; class PhysicsBody; class PhysicsWorld; -typedef Vec2 Vect; - typedef struct CC_DLL PhysicsContactData { static const int POINT_MAX = 4; @@ -162,7 +160,7 @@ public: /** Set the friction.*/ void setFriction(float friction); /** Set the surface velocity.*/ - void setSurfaceVelocity(const Vect& velocity); + void setSurfaceVelocity(const Vec2& velocity); /** Ignore the rest of the contact presolve and postsolve callbacks. */ void ignore(); diff --git a/cocos/physics/CCPhysicsHelper.h b/cocos/physics/CCPhysicsHelper.h index bc2199d48b..a40d317768 100644 --- a/cocos/physics/CCPhysicsHelper.h +++ b/cocos/physics/CCPhysicsHelper.h @@ -64,9 +64,6 @@ public: /** Make cpFloat type convert to float type. */ static float cpfloat2float(cpFloat f) { return f; } - /** Make float type convert to cpFloat type. */ - static cpFloat float2cpfloat(float f) { return f; } - /** Make Rect type convert to cpBB type. */ static cpBB rect2cpbb(const Rect& rect) { return cpBBNew(rect.origin.x, rect.origin.y, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); } diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 351147bfb5..aec0d662c8 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -139,7 +139,7 @@ void PhysicsJoint::setMaxForce(float force) _maxForce = force; for (auto joint : _cpConstraints) { - joint->maxForce = PhysicsHelper::float2cpfloat(force); + joint->maxForce = force; } } @@ -270,8 +270,8 @@ bool PhysicsJointLimit::createConstraints() auto joint = cpSlideJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(), PhysicsHelper::point2cpv(_anchr1), PhysicsHelper::point2cpv(_anchr2), - PhysicsHelper::float2cpfloat(_min), - PhysicsHelper::float2cpfloat(_max)); + _min, + _max); CC_BREAK_IF(joint == nullptr); _cpConstraints.push_back(joint); @@ -289,7 +289,7 @@ float PhysicsJointLimit::getMin() const void PhysicsJointLimit::setMin(float min) { - cpSlideJointSetMin(_cpConstraints.front(), PhysicsHelper::float2cpfloat(min)); + cpSlideJointSetMin(_cpConstraints.front(), min); } float PhysicsJointLimit::getMax() const @@ -299,7 +299,7 @@ float PhysicsJointLimit::getMax() const void PhysicsJointLimit::setMax(float max) { - cpSlideJointSetMax(_cpConstraints.front(), PhysicsHelper::float2cpfloat(max)); + cpSlideJointSetMax(_cpConstraints.front(), max); } Vec2 PhysicsJointLimit::getAnchr1() const @@ -362,7 +362,7 @@ float PhysicsJointDistance::getDistance() const void PhysicsJointDistance::setDistance(float distance) { - cpPinJointSetDist(_cpConstraints.front(), PhysicsHelper::float2cpfloat(distance)); + cpPinJointSetDist(_cpConstraints.front(), distance); } PhysicsJointSpring* PhysicsJointSpring::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2, float stiffness, float damping) @@ -390,9 +390,9 @@ bool PhysicsJointSpring::createConstraints() _bodyB->getCPBody(), PhysicsHelper::point2cpv(_anchr1), PhysicsHelper::point2cpv(_anchr2), - PhysicsHelper::float2cpfloat(_bodyB->local2World(_anchr1).getDistance(_bodyA->local2World(_anchr2))), - PhysicsHelper::float2cpfloat(_stiffness), - PhysicsHelper::float2cpfloat(_damping)); + _bodyB->local2World(_anchr1).getDistance(_bodyA->local2World(_anchr2)), + _stiffness, + _damping); CC_BREAK_IF(joint == nullptr); _cpConstraints.push_back(joint); @@ -430,7 +430,7 @@ float PhysicsJointSpring::getRestLength() const void PhysicsJointSpring::setRestLength(float restLength) { - cpDampedSpringSetRestLength(_cpConstraints.front(), PhysicsHelper::float2cpfloat(restLength)); + cpDampedSpringSetRestLength(_cpConstraints.front(), restLength); } float PhysicsJointSpring::getStiffness() const @@ -440,7 +440,7 @@ float PhysicsJointSpring::getStiffness() const void PhysicsJointSpring::setStiffness(float stiffness) { - cpDampedSpringSetStiffness(_cpConstraints.front(), PhysicsHelper::float2cpfloat(stiffness)); + cpDampedSpringSetStiffness(_cpConstraints.front(), stiffness); } float PhysicsJointSpring::getDamping() const @@ -450,7 +450,7 @@ float PhysicsJointSpring::getDamping() const void PhysicsJointSpring::setDamping(float damping) { - cpDampedSpringSetDamping(_cpConstraints.front(), PhysicsHelper::float2cpfloat(damping)); + cpDampedSpringSetDamping(_cpConstraints.front(), damping); } PhysicsJointGroove* PhysicsJointGroove::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& grooveA, const Vec2& grooveB, const Vec2& anchr2) @@ -539,9 +539,9 @@ bool PhysicsJointRotarySpring::createConstraints() do { auto joint = cpDampedRotarySpringNew(_bodyA->getCPBody(), _bodyB->getCPBody(), - PhysicsHelper::float2cpfloat(_bodyB->getRotation() - _bodyA->getRotation()), - PhysicsHelper::float2cpfloat(_stiffness), - PhysicsHelper::float2cpfloat(_damping)); + _bodyB->getRotation() - _bodyA->getRotation(), + _stiffness, + _damping); CC_BREAK_IF(joint == nullptr); _cpConstraints.push_back(joint); @@ -559,7 +559,7 @@ float PhysicsJointRotarySpring::getRestAngle() const void PhysicsJointRotarySpring::setRestAngle(float restAngle) { - cpDampedRotarySpringSetRestAngle(_cpConstraints.front(), PhysicsHelper::float2cpfloat(restAngle)); + cpDampedRotarySpringSetRestAngle(_cpConstraints.front(), restAngle); } float PhysicsJointRotarySpring::getStiffness() const @@ -569,7 +569,7 @@ float PhysicsJointRotarySpring::getStiffness() const void PhysicsJointRotarySpring::setStiffness(float stiffness) { - cpDampedRotarySpringSetStiffness(_cpConstraints.front(), PhysicsHelper::float2cpfloat(stiffness)); + cpDampedRotarySpringSetStiffness(_cpConstraints.front(), stiffness); } float PhysicsJointRotarySpring::getDamping() const @@ -579,7 +579,7 @@ float PhysicsJointRotarySpring::getDamping() const void PhysicsJointRotarySpring::setDamping(float damping) { - cpDampedRotarySpringSetDamping(_cpConstraints.front(), PhysicsHelper::float2cpfloat(damping)); + cpDampedRotarySpringSetDamping(_cpConstraints.front(), damping); } PhysicsJointRotaryLimit* PhysicsJointRotaryLimit::construct(PhysicsBody* a, PhysicsBody* b, float min, float max) @@ -609,8 +609,8 @@ bool PhysicsJointRotaryLimit::createConstraints() { auto joint = cpRotaryLimitJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(), - PhysicsHelper::float2cpfloat(_min), - PhysicsHelper::float2cpfloat(_max)); + _min, + _max); CC_BREAK_IF(joint == nullptr); _cpConstraints.push_back(joint); @@ -628,7 +628,7 @@ float PhysicsJointRotaryLimit::getMin() const void PhysicsJointRotaryLimit::setMin(float min) { - cpRotaryLimitJointSetMin(_cpConstraints.front(), PhysicsHelper::float2cpfloat(min)); + cpRotaryLimitJointSetMin(_cpConstraints.front(), min); } float PhysicsJointRotaryLimit::getMax() const @@ -638,7 +638,7 @@ float PhysicsJointRotaryLimit::getMax() const void PhysicsJointRotaryLimit::setMax(float max) { - cpRotaryLimitJointSetMax(_cpConstraints.front(), PhysicsHelper::float2cpfloat(max)); + cpRotaryLimitJointSetMax(_cpConstraints.front(), max); } PhysicsJointRatchet* PhysicsJointRatchet::construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratchet) @@ -663,7 +663,7 @@ bool PhysicsJointRatchet::createConstraints() { auto joint = cpRatchetJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(), - PhysicsHelper::float2cpfloat(_phase), + _phase, PhysicsHelper::cpfloat2float(_ratchet)); CC_BREAK_IF(joint == nullptr); @@ -682,7 +682,7 @@ float PhysicsJointRatchet::getAngle() const void PhysicsJointRatchet::setAngle(float angle) { - cpRatchetJointSetAngle(_cpConstraints.front(), PhysicsHelper::float2cpfloat(angle)); + cpRatchetJointSetAngle(_cpConstraints.front(), angle); } float PhysicsJointRatchet::getPhase() const @@ -692,7 +692,7 @@ float PhysicsJointRatchet::getPhase() const void PhysicsJointRatchet::setPhase(float phase) { - cpRatchetJointSetPhase(_cpConstraints.front(), PhysicsHelper::float2cpfloat(phase)); + cpRatchetJointSetPhase(_cpConstraints.front(), phase); } float PhysicsJointRatchet::getRatchet() const @@ -702,7 +702,7 @@ float PhysicsJointRatchet::getRatchet() const void PhysicsJointRatchet::setRatchet(float ratchet) { - cpRatchetJointSetRatchet(_cpConstraints.front(), PhysicsHelper::float2cpfloat(ratchet)); + cpRatchetJointSetRatchet(_cpConstraints.front(), ratchet); } PhysicsJointGear* PhysicsJointGear::construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratio) @@ -727,8 +727,8 @@ bool PhysicsJointGear::createConstraints() { auto joint = cpGearJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(), - PhysicsHelper::float2cpfloat(_phase), - PhysicsHelper::float2cpfloat(_ratio)); + _phase, + _ratio); CC_BREAK_IF(joint == nullptr); _cpConstraints.push_back(joint); @@ -746,7 +746,7 @@ float PhysicsJointGear::getPhase() const void PhysicsJointGear::setPhase(float phase) { - cpGearJointSetPhase(_cpConstraints.front(), PhysicsHelper::float2cpfloat(phase)); + cpGearJointSetPhase(_cpConstraints.front(), phase); } float PhysicsJointGear::getRatio() const @@ -756,7 +756,7 @@ float PhysicsJointGear::getRatio() const void PhysicsJointGear::setRatio(float ratio) { - cpGearJointSetRatio(_cpConstraints.front(), PhysicsHelper::float2cpfloat(ratio)); + cpGearJointSetRatio(_cpConstraints.front(), ratio); } PhysicsJointMotor* PhysicsJointMotor::construct(PhysicsBody* a, PhysicsBody* b, float rate) @@ -780,7 +780,7 @@ bool PhysicsJointMotor::createConstraints() { auto joint = cpSimpleMotorNew(_bodyA->getCPBody(), _bodyB->getCPBody(), - PhysicsHelper::float2cpfloat(_rate)); + _rate); CC_BREAK_IF(joint == nullptr); _cpConstraints.push_back(joint); @@ -798,7 +798,7 @@ float PhysicsJointMotor::getRate() const void PhysicsJointMotor::setRate(float rate) { - cpSimpleMotorSetRate(_cpConstraints.front(), PhysicsHelper::float2cpfloat(rate)); + cpSimpleMotorSetRate(_cpConstraints.front(), rate); } NS_CC_END diff --git a/cocos/physics/CCPhysicsManager.cpp b/cocos/physics/CCPhysicsManager.cpp deleted file mode 100644 index 15a4d40583..0000000000 --- a/cocos/physics/CCPhysicsManager.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "base/ccConfig.h" // to include defination of CC_USE_PHYSICS -#if CC_USE_PHYSICS - -#include "physics/CCPhysicsManager.h" -#include "physics/CCComponentPhysics2d.h" -#include "physics/CCPhysicsWorld.h" -#include "2d/CCScene.h" - -NS_CC_BEGIN - -PhysicsManager::PhysicsManager(Scene *scene) -: _scene(scene) -{ - _physicsWorld = PhysicsWorld::construct(); -} - -PhysicsManager::~PhysicsManager() -{ - delete _physicsWorld; -} - -void PhysicsManager::update(float dt) -{ - // Update physics position, should loop as the same sequence as node tree. - // ComponentPhysics2d::beforeSimulation() will depend on the sequence. - beforeSimulation(_scene); - - // do simulation - _physicsWorld->update(dt, false); - - // Update physics position, should loop as the same sequence as node tree. - // ComponentPhysics2d::afterSimulation() will depend on the sequence. - afterSimulation(_scene); -} - -void PhysicsManager::beforeSimulation(Node *node) -{ - auto iter = _owners.find(node); - if (iter != _owners.end()) - { - auto component = iter->second; - component->beforeSimulation(); - } - - for (auto child : node->getChildren()) - beforeSimulation(child); -} - -void PhysicsManager::afterSimulation(Node *node) -{ - auto iter = _owners.find(node); - if (iter != _owners.end()) - { - auto component = iter->second; - component->afterSimulation(); - } - - for (auto child : node->getChildren()) - afterSimulation(child); -} - -void PhysicsManager::addPhysicsComponent(ComponentPhysics2d* componentPhsics2d) -{ - // don't add component again - if (std::find(_components.begin(), _components.end(), componentPhsics2d) != _components.end()) - return; - - _components.push_back(componentPhsics2d); - // Node::getComponent<>() is a time comsuming operation, so record data to avoid invoking it. - std::pair element(componentPhsics2d->getOwner(), componentPhsics2d); - _owners.insert(element); - - if (nullptr != componentPhsics2d->getPhysicsBody()) - _physicsWorld->addBody(componentPhsics2d->getPhysicsBody()); -} - -void PhysicsManager::removePhysicsComponent(ComponentPhysics2d* componentPhsics2d) -{ - auto iter = std::find(_components.begin(), _components.end(), componentPhsics2d); - if (iter != _components.end()) - { - removeElementFromMap(*iter); - - _components.erase(iter); - if (componentPhsics2d->getPhysicsBody()) - _physicsWorld->removeBody(componentPhsics2d->getPhysicsBody()); - } -} - -void PhysicsManager::removeElementFromMap(ComponentPhysics2d* component) -{ - for (auto element : _owners) - { - if (element.second == component) - { - _owners.erase(element.first); - break; - } - } -} - -PhysicsWorld* PhysicsManager::getPhysicsWorld() const -{ - return _physicsWorld; -} - -NS_CC_END - -#endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsManager.h b/cocos/physics/CCPhysicsManager.h deleted file mode 100644 index 5c1ecc0931..0000000000 --- a/cocos/physics/CCPhysicsManager.h +++ /dev/null @@ -1,124 +0,0 @@ -/**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#pragma once - -#include "base/ccConfig.h" // to include defination of CC_USE_PHYSICS -#if CC_USE_PHYSICS - -#include -#include - -#include "platform/CCPlatformMacros.h" - -NS_CC_BEGIN - -class ComponentPhysics2d; -class PhysicsWorld; -class Scene; -class Node; - -/** - * @addtogroup physics - * @{ - * @addtogroup physics_2d - * @{ - */ - -/** - * Now `PhysicsManager` belongs to a `Scene`. `Scene` will create `PhysicsManager` automatically. - * The reason to design like this are: - * - PhysicsManager keeps physics world, it is reasonale that a scene has its own physics world. - * It is useful that when a scene is active again, you don't have to create physics world and - * do all related things again. - * - Keep compatibility - */ -class CC_DLL PhysicsManager -{ -public: - - /// @cond DO_NOT_SHOW - - /** - * Create a PhysicsManager with `Scene`. `Scene` will create it automatically, - * so don't create it yourself. - * - * @scene The scene this `PhysicsManager` belongs to. - */ - PhysicsManager(Scene *scene); - /** - * Destructor. - */ - ~PhysicsManager(); - - /** - * Do physics simulation. It will do the following things: - * - synchronize Node's status(position, rotation, scale) to corresponding physics body - * - do physics simulation - * - synchronize physics body's status(position, rotation) to correspondind Node - * - * It is invoked by `Scene`, don't invoke it yourself. - */ - void update(float dt); - - /// @endcond DO_NOT_SHOW - - /** - * Get the physics world. - * - * @return Physics world managed by this `PhysicsManager`. - */ - PhysicsWorld* getPhysicsWorld() const; - - /** - * Add a physics component to be managed by the `PhysicsManager`. Will register physics - * component's physics body to physics world managed by this `PhysicsManager`. - * - * @param componentPhsics2d The physics component to be managed by this `PhysicsManager`. - */ - void addPhysicsComponent(ComponentPhysics2d* componentPhsics2d); - /** - * Remove a physics component from `PhysiscsManager`. Will remove physics component's physics - * body from the physics world managed by this `PhysicsManager`. - */ - void removePhysicsComponent(ComponentPhysics2d* componentPhsics2d); - -private: - void beforeSimulation(Node *node); - void afterSimulation(Node* node); - void removeElementFromMap(ComponentPhysics2d* component); -private: - std::vector _components; - // record the owners of components for performance - std::unordered_map _owners; - PhysicsWorld *_physicsWorld; - Scene *_scene; -}; - -/** @} */ -/** @} */ - -NS_CC_END - -#endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 9f5116305e..ed67ab6e05 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -233,7 +233,7 @@ void PhysicsShape::setDensity(float density) setMass(PHYSICS_INFINITY); }else if (_area > 0) { - setMass(PhysicsHelper::float2cpfloat(_material.density * _area)); + setMass(_material.density * _area); } } @@ -243,7 +243,7 @@ void PhysicsShape::setRestitution(float restitution) for (cpShape* shape : _cpShapes) { - cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(restitution)); + cpShapeSetElasticity(shape, restitution); } } @@ -253,7 +253,7 @@ void PhysicsShape::setFriction(float friction) for (cpShape* shape : _cpShapes) { - cpShapeSetFriction(shape, PhysicsHelper::float2cpfloat(friction)); + cpShapeSetFriction(shape, friction); } } @@ -359,9 +359,9 @@ float PhysicsShapeCircle::calculateArea(float radius) float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Vec2& offset) { return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY - : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), + : PhysicsHelper::cpfloat2float(cpMomentForCircle(mass, 0, - PhysicsHelper::float2cpfloat(radius), + radius, PhysicsHelper::point2cpv(offset))); } @@ -375,7 +375,7 @@ float PhysicsShapeCircle::calculateDefaultMoment() auto shape = _cpShapes.front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY - : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), + : PhysicsHelper::cpfloat2float(cpMomentForCircle(_mass, 0, cpCircleShapeGetRadius(shape), cpCircleShapeGetOffset(shape))); @@ -393,11 +393,11 @@ Vec2 PhysicsShapeCircle::getOffset() void PhysicsShapeCircle::updateScale() { - cpFloat factor = std::abs(PhysicsHelper::float2cpfloat(_newScaleX / _scaleX)); + cpFloat factor = std::abs(_newScaleX / _scaleX); cpShape* shape = _cpShapes.front(); cpVect v = cpCircleShapeGetOffset(shape); - v = cpvmult(v, PhysicsHelper::float2cpfloat(factor)); + v = cpvmult(v, factor); ((cpCircleShape*)shape)->c = v; cpCircleShapeSetRadius(shape, cpCircleShapeGetRadius(shape) * factor); @@ -428,7 +428,7 @@ bool PhysicsShapeEdgeSegment::init(const Vec2& a, const Vec2& b, const PhysicsMa auto shape = cpSegmentShapeNew(s_sharedBody, PhysicsHelper::point2cpv(a), PhysicsHelper::point2cpv(b), - PhysicsHelper::float2cpfloat(border)); + border); CC_BREAK_IF(shape == nullptr); @@ -464,8 +464,8 @@ Vec2 PhysicsShapeEdgeSegment::getCenter() void PhysicsShapeEdgeSegment::updateScale() { - cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); - cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); + cpFloat factorX = _newScaleX / _scaleX; + cpFloat factorY = _newScaleY / _scaleY; cpShape* shape = _cpShapes.front(); cpVect a = cpSegmentShapeGetA(shape); @@ -628,8 +628,8 @@ Vec2 PhysicsShapePolygon::getCenter() void PhysicsShapePolygon::updateScale() { - cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); - cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); + cpFloat factorX = _newScaleX / _scaleX; + cpFloat factorY = _newScaleY / _scaleY; auto shape = _cpShapes.front(); int count = cpPolyShapeGetNumVerts(shape); @@ -697,8 +697,7 @@ bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material int i = 0; for (; i < 4; ++i) { - auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % 4], - PhysicsHelper::float2cpfloat(border)); + auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % 4], border); CC_BREAK_IF(shape == nullptr); addShape(shape); } @@ -742,8 +741,7 @@ bool PhysicsShapeEdgePolygon::init(const Vec2* points, int count, const PhysicsM int i = 0; for (; i < count; ++i) { - auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % count], - PhysicsHelper::float2cpfloat(border)); + auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % count], border); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); cpShapeSetFriction(shape, 1.0f); @@ -812,8 +810,8 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(const Vec2* points, int cou void PhysicsShapeEdgePolygon::updateScale() { - cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); - cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); + cpFloat factorX = _newScaleX / _scaleX; + cpFloat factorY = _newScaleY / _scaleY; for (auto shape : _cpShapes) { @@ -842,8 +840,7 @@ bool PhysicsShapeEdgeChain::init(const Vec2* points, int count, const PhysicsMat int i = 0; for (; i < count - 1; ++i) { - auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[i + 1], - PhysicsHelper::float2cpfloat(border)); + auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[i + 1], border); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); cpShapeSetFriction(shape, 1.0f); @@ -901,8 +898,8 @@ int PhysicsShapeEdgeChain::getPointsCount() const void PhysicsShapeEdgeChain::updateScale() { - cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); - cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); + cpFloat factorX = _newScaleX / _scaleX; + cpFloat factorY = _newScaleY / _scaleY; for (auto shape : _cpShapes) { diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 1ceb0824f4..061de85c3f 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -281,7 +281,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { contact.setEventCode(PhysicsContact::EventCode::BEGIN); contact.setWorld(this); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); + _eventDispatcher->dispatchEvent(&contact); } return ret ? contact.resetResult() : false; @@ -296,7 +296,7 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) contact.setEventCode(PhysicsContact::EventCode::PRESOLVE); contact.setWorld(this); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); + _eventDispatcher->dispatchEvent(&contact); return contact.resetResult(); } @@ -310,7 +310,7 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE); contact.setWorld(this); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); + _eventDispatcher->dispatchEvent(&contact); } void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) @@ -322,7 +322,7 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) contact.setEventCode(PhysicsContact::EventCode::SEPARATE); contact.setWorld(this); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); + _eventDispatcher->dispatchEvent(&contact); } void PhysicsWorld::rayCast(PhysicsRayCastCallbackFunc func, const Vec2& point1, const Vec2& point2, void* data) @@ -419,18 +419,6 @@ PhysicsShape* PhysicsWorld::getShape(const Vec2& point) const return shape == nullptr ? nullptr : s_physicsShapeMap.find(shape)->second; } -PhysicsWorld* PhysicsWorld::construct() -{ - PhysicsWorld * world = new (std::nothrow) PhysicsWorld(); - if(world && world->init()) - { - return world; - } - - CC_SAFE_DELETE(world); - return nullptr; -} - bool PhysicsWorld::init() { do @@ -561,7 +549,6 @@ void PhysicsWorld::removeBody(PhysicsBody* body) body->_world = nullptr; } - void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) { if (_delayAddBodies.getIndex(body) != CC_INVALID_INDEX) @@ -780,7 +767,7 @@ PhysicsBody* PhysicsWorld::getBody(int tag) const return nullptr; } -void PhysicsWorld::setGravity(const Vect& gravity) +void PhysicsWorld::setGravity(const Vec2& gravity) { _gravity = gravity; cpSpaceSetGravity(_cpSpace, PhysicsHelper::point2cpv(gravity)); @@ -821,6 +808,9 @@ void PhysicsWorld::update(float delta, bool userCall/* = false*/) updateBodies(); } + auto sceneToWorldTransform = _scene->getNodeToParentTransform(); + beforeSimulation(_scene, sceneToWorldTransform, 1.f, 1.f, 0.f); + if (!_delayAddJoints.empty() || !_delayRemoveJoints.empty()) { updateJoints(); @@ -862,6 +852,24 @@ void PhysicsWorld::update(float delta, bool userCall/* = false*/) { debugDraw(); } + + // Update physics position, should loop as the same sequence as node tree. + // PhysicsWorld::afterSimulation() will depend on the sequence. + afterSimulation(_scene, sceneToWorldTransform, 0.f); +} + +PhysicsWorld* PhysicsWorld::construct(Scene* scene) +{ + PhysicsWorld * world = new (std::nothrow) PhysicsWorld(); + if (world && world->init()) + { + world->_scene = scene; + world->_eventDispatcher = scene->getEventDispatcher(); + return world; + } + + CC_SAFE_DELETE(world); + return nullptr; } PhysicsWorld::PhysicsWorld() @@ -877,6 +885,7 @@ PhysicsWorld::PhysicsWorld() , _autoStep(true) , _debugDraw(nullptr) , _debugDrawMask(DEBUGDRAW_NONE) +, _eventDispatcher(nullptr) { } @@ -892,6 +901,40 @@ PhysicsWorld::~PhysicsWorld() CC_SAFE_DELETE(_debugDraw); } +void PhysicsWorld::beforeSimulation(Node *node, const Mat4& parentToWorldTransform, float nodeParentScaleX, float nodeParentScaleY, float parentRotation) +{ + auto scaleX = nodeParentScaleX * node->getScaleX(); + auto scaleY = nodeParentScaleY * node->getScaleY(); + auto rotation = parentRotation + node->getRotation(); + + auto nodeToWorldTransform = parentToWorldTransform * node->getNodeToParentTransform(); + + auto physicsBody = node->getPhysicsBody(); + if (physicsBody) + { + physicsBody->beforeSimulation(parentToWorldTransform, nodeToWorldTransform, scaleX, scaleY, rotation); + } + + for (auto child : node->getChildren()) + beforeSimulation(child, nodeToWorldTransform, scaleX, scaleY, rotation); +} + +void PhysicsWorld::afterSimulation(Node *node, const Mat4& parentToWorldTransform, float parentRotation) +{ + auto nodeToWorldTransform = parentToWorldTransform * node->getNodeToParentTransform(); + auto nodeRotation = parentRotation + node->getRotation(); + + auto physicsBody = node->getPhysicsBody(); + if (physicsBody) + { + physicsBody->afterSimulation(parentToWorldTransform, parentRotation); + } + + for (auto child : node->getChildren()) + afterSimulation(child, nodeToWorldTransform, nodeRotation); +} + + PhysicsDebugDraw::PhysicsDebugDraw(PhysicsWorld& world) : _drawNode(nullptr) , _world(world) diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 107dcac932..4d05f926ce 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -28,11 +28,10 @@ #include "base/ccConfig.h" #if CC_USE_PHYSICS +#include #include "base/CCVector.h" -#include "base/CCRef.h" #include "math/CCGeometry.h" #include "physics/CCPhysicsBody.h" -#include struct cpSpace; @@ -43,14 +42,13 @@ class PhysicsJoint; class PhysicsShape; class PhysicsContact; -typedef Vec2 Vect; - class Director; class Node; class Sprite; class Scene; class DrawNode; class PhysicsDebugDraw; +class EventDispatcher; class PhysicsWorld; @@ -60,7 +58,7 @@ typedef struct PhysicsRayCastInfo Vec2 start; Vec2 end; //< in lua, it's name is "ended" Vec2 contact; - Vect normal; + Vec2 normal; float fraction; void* data; }PhysicsRayCastInfo; @@ -228,16 +226,16 @@ public: /** * Get the gravity value of this physics world. * - * @return A Vect object. + * @return A Vec2 object. */ - inline Vect getGravity() const { return _gravity; } + inline Vec2 getGravity() const { return _gravity; } /** * set the gravity value of this physics world. * * @param gravity A gravity value of this physics world. */ - void setGravity(const Vect& gravity); + void setGravity(const Vec2& gravity); /** * Set the speed of this physics world. @@ -329,7 +327,7 @@ public: void step(float delta); protected: - static PhysicsWorld* construct(); + static PhysicsWorld* construct(Scene* scene); bool init(); @@ -354,7 +352,7 @@ protected: virtual void updateJoints(); protected: - Vect _gravity; + Vec2 _gravity; float _speed; int _updateRate; int _updateRateCount; @@ -371,7 +369,8 @@ protected: PhysicsDebugDraw* _debugDraw; int _debugDrawMask; - + EventDispatcher* _eventDispatcher; + Vector _delayAddBodies; Vector _delayRemoveBodies; std::vector _delayAddJoints; @@ -381,6 +380,9 @@ protected: PhysicsWorld(); virtual ~PhysicsWorld(); + void beforeSimulation(Node *node, const Mat4& parentToWorldTransform, float nodeParentScaleX, float nodeParentScaleY, float parentRotation); + void afterSimulation(Node* node, const Mat4& parentToWorldTransform, float parentRotation); + friend class Node; friend class Sprite; friend class Scene; @@ -390,7 +392,6 @@ protected: friend class PhysicsJoint; friend class PhysicsWorldCallback; friend class PhysicsDebugDraw; - friend class PhysicsManager; }; /** A physics helper class. Draw physics shape, joint in debug mode. diff --git a/cocos/physics/CMakeLists.txt b/cocos/physics/CMakeLists.txt index 4a2b9447d6..b31b4adef5 100644 --- a/cocos/physics/CMakeLists.txt +++ b/cocos/physics/CMakeLists.txt @@ -6,6 +6,4 @@ set(COCOS_PHYSICS_SRC physics/CCPhysicsJoint.cpp physics/CCPhysicsShape.cpp physics/CCPhysicsWorld.cpp - physics/CCComponentPhysics2d.cpp - physics/CCPhysicsManager.cpp ) diff --git a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp index b63d7b63fd..5ea1335c24 100644 --- a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp +++ b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp @@ -4,7 +4,6 @@ #include #include "ui/CocosGUI.h" -#include "physics/CCComponentPhysics2d.h" #include "../testResource.h" USING_NS_CC; @@ -98,8 +97,7 @@ Sprite* PhysicsDemo::addGrossiniAtPosition(Vec2 p, float scale/* = 1.0*/) sp->setScale(scale); sp->setPosition(p); - addPhysicsComponent(sp, PhysicsBody::createBox(Size(48.0f, 108.0f))); - //addPhysicsComponent(sp, PhysicsBody::createCircle(sp->getContentSize().height/2)); + sp->addComponent(PhysicsBody::createBox(Size(48.0f, 108.0f))); this->addChild(sp); return sp; @@ -173,7 +171,7 @@ Sprite* PhysicsDemo::makeBall(Vec2 point, float radius, PhysicsMaterial material ball->setScale(0.13f * radius); - addPhysicsComponent(ball, PhysicsBody::createCircle(ball->getContentSize().width / 2, material)); + ball->addComponent(PhysicsBody::createCircle(ball->getContentSize().width / 2, material)); ball->setPosition(Vec2(point.x, point.y)); return ball; @@ -195,7 +193,7 @@ Sprite* PhysicsDemo::makeBox(Vec2 point, Size size, int color, PhysicsMaterial m box->setScaleX(size.width / 100.0f); box->setScaleY(size.height / 100.0f); - addPhysicsComponent(box, PhysicsBody::createBox(box->getContentSize(), material)); + box->addComponent(PhysicsBody::createBox(box->getContentSize(), material)); box->setPosition(Vec2(point.x, point.y)); @@ -228,7 +226,7 @@ Sprite* PhysicsDemo::makeTriangle(Vec2 point, Size size, int color, PhysicsMater Vec2 vers[] = { Vec2(0, triangle->getContentSize().height / 2), Vec2(triangle->getContentSize().width / 2, -triangle->getContentSize().height / 2), Vec2(-triangle->getContentSize().width / 2, -triangle->getContentSize().height / 2) }; - addPhysicsComponent(triangle, PhysicsBody::createPolygon(vers, 3, material)); + triangle->addComponent(PhysicsBody::createPolygon(vers, 3, material)); triangle->setPosition(Vec2(point.x, point.y)); return triangle; @@ -254,7 +252,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) Node* mouse = Node::create(); auto physicsBody = PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY); physicsBody->setDynamic(false); - addPhysicsComponent(mouse, physicsBody); + mouse->addComponent(physicsBody); mouse->setPosition(location); this->addChild(mouse); PhysicsJointPin* joint = PhysicsJointPin::construct(physicsBody, body, location); @@ -289,13 +287,6 @@ void PhysicsDemo::onTouchEnded(Touch* touch, Event* event) } } -void PhysicsDemo::addPhysicsComponent(Node *node, PhysicsBody *physicsBody) -{ - auto physicsComponent = ComponentPhysics2d::create(); - physicsComponent->setPhysicsBody(physicsBody); - node->addComponent(physicsComponent); -} - // Implementation of PhysicsComponentDemoLogoSmash void PhysicsDemoLogoSmash::onEnter() @@ -320,7 +311,7 @@ void PhysicsDemoLogoSmash::onEnter() 2*(LOGO_HEIGHT-y + yJitter) + VisibleRect::getVisibleRect().size.height/2 - LOGO_HEIGHT/2), 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); - auto physicsBody = ball->getComponent()->getPhysicsBody(); + auto physicsBody = ball->getPhysicsBody(); physicsBody->setMass(1.0); physicsBody->setMoment(PHYSICS_INFINITY); @@ -331,7 +322,7 @@ void PhysicsDemoLogoSmash::onEnter() auto bullet = makeBall(Vec2(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); - bullet->getComponent()->getPhysicsBody()->setVelocity(Vec2(200, 0)); + bullet->getPhysicsBody()->setVelocity(Vec2(200, 0)); bullet->setPosition(Vec2(-500, VisibleRect::getVisibleRect().size.height/2)); @@ -363,7 +354,7 @@ void PhysicsDemoClickAdd::onEnter() _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); auto node = Node::create(); - addPhysicsComponent(node, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + node->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); node->setPosition(VisibleRect::center()); this->addChild(node); @@ -416,14 +407,16 @@ void PhysicsDemoPyramidStack::onEnter() _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto node = Node::create(); - addPhysicsComponent(node, PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50))); + node->addComponent(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), + VisibleRect::rightBottom() + Vec2(0, 50))); this->addChild(node); auto ball = Sprite::create("Images/ball.png"); ball->setScale(1); ball->setTag(100); - addPhysicsComponent(ball, PhysicsBody::createCircle(10)); - ball->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto body = PhysicsBody::createCircle(10); + ball->addComponent(body); + body->setTag(DRAG_BODYS_TAG); ball->setPosition(VisibleRect::bottom() + Vec2(0, 60)); this->addChild(ball); @@ -434,7 +427,7 @@ void PhysicsDemoPyramidStack::onEnter() for (int j = 0; j <= i; j++) { auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Vec2((i / 2 - j) * 11, (14 - i) * 23 + 100), 0.2f); - sp->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + sp->getPhysicsBody()->setTag(DRAG_BODYS_TAG); } } } @@ -468,7 +461,7 @@ void PhysicsDemoRayCast::onEnter() _physicsWorld->setGravity(Point::ZERO); auto node = DrawNode::create(); - addPhysicsComponent(node, PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50))); + node->addComponent(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50))); node->drawSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50), 1, STATIC_COLOR); this->addChild(node); @@ -632,7 +625,7 @@ std::string PhysicsDemoRayCast::title() const void PhysicsDemoActions::onEnter() { PhysicsDemo::onEnter(); - _physicsWorld->setGravity(Vect::ZERO); + _physicsWorld->setGravity(Vec2::ZERO); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoActions::onTouchBegan, this); @@ -641,7 +634,7 @@ void PhysicsDemoActions::onEnter() _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto node = Node::create(); - addPhysicsComponent(node, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + node->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); node->setPosition(VisibleRect::center()); this->addChild(node); @@ -649,12 +642,12 @@ void PhysicsDemoActions::onEnter() Sprite* sp2 = addGrossiniAtPosition(VisibleRect::left() + Vec2(50, 0)); Sprite* sp3 = addGrossiniAtPosition(VisibleRect::right() - Vec2(20, 0)); Sprite* sp4 = addGrossiniAtPosition(VisibleRect::leftTop() + Vec2(50, -50)); - sp4->getComponent()->getPhysicsBody()->setGravityEnable(false); + sp4->getPhysicsBody()->setGravityEnable(false); - sp1->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - sp2->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - sp3->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - sp4->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + sp3->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + sp4->getPhysicsBody()->setTag(DRAG_BODYS_TAG); auto actionTo = JumpTo::create(2, Vec2(100, 100), 50, 4); auto actionBy = JumpBy::create(2, Vec2(300, 0), 50, 4); @@ -693,7 +686,7 @@ void PhysicsDemoJoints::onEnter() Node* node = Node::create(); PhysicsBody* box = PhysicsBody::create(); - addPhysicsComponent(node, box); + node->addComponent(box); box->setDynamic(false); node->setPosition(Point::ZERO); @@ -711,11 +704,11 @@ void PhysicsDemoJoints::onEnter() case 0: { auto sp1 = makeBall(offset - Vec2(30, 0), 10); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBall(offset + Vec2(30, 0), 10); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); PhysicsJointPin* joint = PhysicsJointPin::construct(sp1PhysicsBody, sp2PhysicsBody, offset); @@ -729,11 +722,11 @@ void PhysicsDemoJoints::onEnter() { auto sp1 = makeBall(offset - Vec2(30, 0), 10); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); PhysicsJointFixed* joint = PhysicsJointFixed::construct(sp1PhysicsBody, sp2PhysicsBody, offset); @@ -746,11 +739,11 @@ void PhysicsDemoJoints::onEnter() case 2: { auto sp1 = makeBall(offset - Vec2(30, 0), 10); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); PhysicsJointDistance* joint = PhysicsJointDistance::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO); @@ -763,11 +756,11 @@ void PhysicsDemoJoints::onEnter() case 3: { auto sp1 = makeBall(offset - Vec2(30, 0), 10); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); PhysicsJointLimit* joint = PhysicsJointLimit::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO, 30.0f, 60.0f); @@ -780,11 +773,11 @@ void PhysicsDemoJoints::onEnter() case 4: { auto sp1 = makeBall(offset - Vec2(30, 0), 10); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); PhysicsJointSpring* joint = PhysicsJointSpring::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO, 500.0f, 0.3f); @@ -797,11 +790,11 @@ void PhysicsDemoJoints::onEnter() case 5: { auto sp1 = makeBall(offset - Vec2(30, 0), 10); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); PhysicsJointGroove* joint = PhysicsJointGroove::construct(sp1PhysicsBody, sp2PhysicsBody, Vec2(30, 15), Vec2(30, -15), Vec2(-30, 0)); @@ -814,11 +807,11 @@ void PhysicsDemoJoints::onEnter() case 6: { auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); @@ -833,11 +826,11 @@ void PhysicsDemoJoints::onEnter() case 7: { auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); @@ -852,11 +845,11 @@ void PhysicsDemoJoints::onEnter() case 8: { auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); @@ -871,11 +864,11 @@ void PhysicsDemoJoints::onEnter() case 9: { auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); @@ -890,11 +883,11 @@ void PhysicsDemoJoints::onEnter() case 10: { auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); - auto sp1PhysicsBody = sp1->getComponent()->getPhysicsBody(); + auto sp1PhysicsBody = sp1->getPhysicsBody(); sp1PhysicsBody->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); - auto sp2PhysicsBody = sp2->getComponent()->getPhysicsBody(); + auto sp2PhysicsBody = sp2->getPhysicsBody(); sp2PhysicsBody->setTag(DRAG_BODYS_TAG); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); @@ -933,19 +926,20 @@ void PhysicsDemoPump::onEnter() scheduleUpdate(); auto node = Node::create(); - addPhysicsComponent(node, PhysicsBody::create()); - node->getComponent()->getPhysicsBody()->setDynamic(false); + auto nodeBody = PhysicsBody::create(); + node->addComponent(nodeBody); + nodeBody->setDynamic(false); PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); - node->getComponent()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, 0), VisibleRect::leftTop() + Vec2(50, -130), staticMaterial, 2.0f)); - node->getComponent()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(190, 0), VisibleRect::leftTop() + Vec2(100, -50), staticMaterial, 2.0f)); - node->getComponent()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -50), VisibleRect::leftTop() + Vec2(100, -90), staticMaterial, 2.0f)); - node->getComponent()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, -130), VisibleRect::leftTop() + Vec2(100, -145), staticMaterial, 2.0f)); - node->getComponent()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -145), VisibleRect::leftBottom() + Vec2(100, 80), staticMaterial, 2.0f)); - node->getComponent()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(150, -80), VisibleRect::leftBottom() + Vec2(150, 80), staticMaterial, 2.0f)); - node->getComponent()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(150, -80), VisibleRect::rightTop() + Vec2(-100, -150), staticMaterial, 2.0f)); + nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, 0), VisibleRect::leftTop() + Vec2(50, -130), staticMaterial, 2.0f)); + nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(190, 0), VisibleRect::leftTop() + Vec2(100, -50), staticMaterial, 2.0f)); + nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -50), VisibleRect::leftTop() + Vec2(100, -90), staticMaterial, 2.0f)); + nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, -130), VisibleRect::leftTop() + Vec2(100, -145), staticMaterial, 2.0f)); + nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -145), VisibleRect::leftBottom() + Vec2(100, 80), staticMaterial, 2.0f)); + nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(150, -80), VisibleRect::leftBottom() + Vec2(150, 80), staticMaterial, 2.0f)); + nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(150, -80), VisibleRect::rightTop() + Vec2(-100, -150), staticMaterial, 2.0f)); - node->getComponent()->getPhysicsBody()->setCategoryBitmask(0x01); + nodeBody->setCategoryBitmask(0x01); node->setPosition(Vec2::ZERO); this->addChild(node); @@ -953,7 +947,7 @@ void PhysicsDemoPump::onEnter() for (int i = 0; i < 6; ++i) { auto ball = makeBall(VisibleRect::leftTop() + Vec2(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.05f, 0.0f, 0.1f)); - ball->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); addChild(ball); } @@ -969,49 +963,55 @@ void PhysicsDemoPump::onEnter() auto pump = Node::create(); auto center = PhysicsShape::getPolyonCenter(vec, 4); pump->setPosition(center); - addPhysicsComponent(pump, PhysicsBody::createPolygon(vec, 4, PHYSICSBODY_MATERIAL_DEFAULT, -center)); + auto pumpBody = PhysicsBody::createPolygon(vec, 4, PHYSICSBODY_MATERIAL_DEFAULT, -center); + pump->addComponent(pumpBody); this->addChild(pump); - pump->getComponent()->getPhysicsBody()->setCategoryBitmask(0x02); - pump->getComponent()->getPhysicsBody()->setGravityEnable(false); + pumpBody->setCategoryBitmask(0x02); + pumpBody->setGravityEnable(false); - // small gear + // small gear + auto sgearBody = PhysicsBody::createCircle(44); + sgearBody->setCategoryBitmask(0x04); + sgearBody->setCollisionBitmask(0x04); + sgearBody->setTag(1); auto sgear = Node::create(); - addPhysicsComponent(sgear, PhysicsBody::createCircle(44)); + sgear->addComponent(sgearBody); sgear->setPosition(VisibleRect::leftBottom() + Vec2(125, 0)); this->addChild(sgear); - sgear->getComponent()->getPhysicsBody()->setCategoryBitmask(0x04); - sgear->getComponent()->getPhysicsBody()->setCollisionBitmask(0x04); - sgear->getComponent()->getPhysicsBody()->setTag(1); - _physicsWorld->addJoint(PhysicsJointPin::construct(node->getComponent()->getPhysicsBody(), sgear->getComponent()->getPhysicsBody(), sgear->getPosition())); - _physicsWorld->addJoint(PhysicsJointDistance::construct(pump->getComponent()->getPhysicsBody(), sgear->getComponent()->getPhysicsBody(), Vec2(0, 0), Vec2(0, -44))); + _physicsWorld->addJoint(PhysicsJointPin::construct(nodeBody, sgearBody, sgear->getPosition())); + _physicsWorld->addJoint(PhysicsJointDistance::construct(pumpBody, sgearBody, Vec2(0, 0), Vec2(0, -44))); - // big gear + // big gear + auto bgearBody = PhysicsBody::createCircle(100); + bgearBody->setCategoryBitmask(0x04); auto bgear = Node::create(); - addPhysicsComponent(bgear, PhysicsBody::createCircle(100)); + bgear->addComponent(bgearBody); bgear->setPosition(VisibleRect::leftBottom() + Vec2(275, 0)); this->addChild(bgear); - bgear->getComponent()->getPhysicsBody()->setCategoryBitmask(0x04); - _physicsWorld->addJoint(PhysicsJointPin::construct(bgear->getComponent()->getPhysicsBody(), node->getComponent()->getPhysicsBody(), bgear->getPosition())); - _physicsWorld->addJoint(PhysicsJointGear::construct(sgear->getComponent()->getPhysicsBody(), bgear->getComponent()->getPhysicsBody(), (float)-M_PI_2, -2.0f)); + _physicsWorld->addJoint(PhysicsJointPin::construct(bgearBody, nodeBody, bgear->getPosition())); + _physicsWorld->addJoint(PhysicsJointGear::construct(sgearBody, bgearBody, (float)-M_PI_2, -2.0f)); // plugger Vec2 seg[] = { VisibleRect::leftTop() + Vec2(75, -120), VisibleRect::leftBottom() + Vec2(75, -100) }; Vec2 segCenter = (seg[1] + seg[0]) / 2; seg[1] -= segCenter; seg[0] -= segCenter; + + auto pluggerBody = PhysicsBody::createEdgeSegment(seg[0], seg[1], PhysicsMaterial(0.01f, 0.0f, 0.5f), 20); + pluggerBody->setDynamic(true); + pluggerBody->setMass(30); + pluggerBody->setMoment(100000); + pluggerBody->setCategoryBitmask(0x02); auto plugger = Node::create(); - addPhysicsComponent(plugger, PhysicsBody::createEdgeSegment(seg[0], seg[1], PhysicsMaterial(0.01f, 0.0f, 0.5f), 20)); - plugger->getComponent()->getPhysicsBody()->setDynamic(true); - plugger->getComponent()->getPhysicsBody()->setMass(30); - plugger->getComponent()->getPhysicsBody()->setMoment(100000); + plugger->addComponent(pluggerBody); plugger->setPosition(segCenter); this->addChild(plugger); - plugger->getComponent()->getPhysicsBody()->setCategoryBitmask(0x02); - sgear->getComponent()->getPhysicsBody()->setCollisionBitmask(0x04 | 0x01); - _physicsWorld->addJoint(PhysicsJointPin::construct(node->getComponent()->getPhysicsBody(), plugger->getComponent()->getPhysicsBody(), VisibleRect::leftBottom() + Vec2(75, -90))); - _physicsWorld->addJoint(PhysicsJointDistance::construct(plugger->getComponent()->getPhysicsBody(), sgear->getComponent()->getPhysicsBody(), Vec2::ZERO, Vec2(44, 0))); + + sgearBody->setCollisionBitmask(0x04 | 0x01); + _physicsWorld->addJoint(PhysicsJointPin::construct(nodeBody, pluggerBody, VisibleRect::leftBottom() + Vec2(75, -90))); + _physicsWorld->addJoint(PhysicsJointDistance::construct(pluggerBody, sgearBody, Vec2::ZERO, Vec2(44, 0))); } void PhysicsDemoPump::update(float delta) @@ -1090,22 +1090,25 @@ void PhysicsDemoOneWayPlatform::onEnter() _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto ground = Node::create(); - addPhysicsComponent(ground, PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50))); + ground->addComponent(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), + VisibleRect::rightBottom() + Vec2(0, 50))); this->addChild(ground); auto platform = makeBox(VisibleRect::center(), Size(200, 50)); - platform->getComponent()->getPhysicsBody()->setDynamic(false); - platform->getComponent()->getPhysicsBody()->setContactTestBitmask(0xFFFFFFFF); + auto platformBody = platform->getPhysicsBody(); + platformBody->setDynamic(false); + platformBody->setContactTestBitmask(0xFFFFFFFF); this->addChild(platform); auto ball = makeBall(VisibleRect::center() - Vec2(0, 50), 20); - ball->getComponent()->getPhysicsBody()->setVelocity(Vec2(0, 150)); - ball->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - ball->getComponent()->getPhysicsBody()->setMass(1.0f); - ball->getComponent()->getPhysicsBody()->setContactTestBitmask(0xFFFFFFFF); + auto ballBody = ball->getPhysicsBody(); + ballBody->setVelocity(Vec2(0, 150)); + ballBody->setTag(DRAG_BODYS_TAG); + ballBody->setMass(1.0f); + ballBody->setContactTestBitmask(0xFFFFFFFF); this->addChild(ball); - auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getComponent()->getPhysicsBody(), ball->getComponent()->getPhysicsBody()); + auto contactListener = EventListenerPhysicsContactWithBodies::create(platformBody, ballBody); contactListener->onContactBegin = CC_CALLBACK_1(PhysicsDemoOneWayPlatform::onContactBegin, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); } @@ -1133,14 +1136,14 @@ void PhysicsDemoSlice::onEnter() _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto ground = Node::create(); - addPhysicsComponent(ground, PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50))); + ground->addComponent(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50))); this->addChild(ground); auto box = Node::create(); Vec2 points[4] = {Vec2(-100, -100), Vec2(-100, 100), Vec2(100, 100), Vec2(100, -100)}; - addPhysicsComponent(box, PhysicsBody::createPolygon(points, 4)); + box->addComponent(PhysicsBody::createPolygon(points, 4)); box->setPosition(VisibleRect::center()); - box->getComponent()->getPhysicsBody()->setTag(_sliceTag); + box->getPhysicsBody()->setTag(_sliceTag); addChild(box); } @@ -1199,7 +1202,7 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Vec2 normal, float d Node* node = Node::create(); PhysicsBody* polyon = PhysicsBody::createPolygon(points, pointsCount, PHYSICSBODY_MATERIAL_DEFAULT, -center); node->setPosition(center); - addPhysicsComponent(node, polyon); + node->addComponent(polyon); polyon->setVelocity(body->getVelocityAtWorldPoint(center)); polyon->setAngularVelocity(body->getAngularVelocity()); polyon->setTag(_sliceTag); @@ -1228,7 +1231,7 @@ void PhysicsDemoBug3988::onEnter() { PhysicsDemo::onEnter(); toggleDebug(); - _physicsWorld->setGravity(Vect::ZERO); + _physicsWorld->setGravity(Vec2::ZERO); auto ball = Sprite::create("Images/YellowSquare.png"); ball->setPosition(VisibleRect::center() - Vec2(100, 0)); @@ -1253,7 +1256,7 @@ std::string PhysicsDemoBug3988::subtitle() const void PhysicsContactTest::onEnter() { PhysicsDemo::onEnter(); - _physicsWorld->setGravity(Vect::ZERO); + _physicsWorld->setGravity(Vec2::ZERO); auto s = VisibleRect::getVisibleRect().size; _yellowBoxNum = 50; @@ -1410,7 +1413,7 @@ void PhysicsContactTest::resetTest() label->setPosition(Vec2(s.width / 2, s.height - 170)); auto wall = Node::create(); - addPhysicsComponent(wall, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1, 0.0f))); + wall->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1, 0.0f))); wall->setPosition(VisibleRect::center()); root->addChild(wall); @@ -1427,12 +1430,13 @@ void PhysicsContactTest::resetTest() position.x = position.x * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); - Vect velocity((CCRANDOM_0_1() - 0.5) * 200, (CCRANDOM_0_1() - 0.5) * 200); + Vec2 velocity((CCRANDOM_0_1() - 0.5) * 200, (CCRANDOM_0_1() - 0.5) * 200); auto box = makeBox(position, size, 1, PhysicsMaterial(0.1f, 1, 0.0f)); - box->getComponent()->getPhysicsBody()->setVelocity(velocity); - box->getComponent()->getPhysicsBody()->setCategoryBitmask(0x01); // 0001 - box->getComponent()->getPhysicsBody()->setContactTestBitmask(0x04); // 0100 - box->getComponent()->getPhysicsBody()->setCollisionBitmask(0x03); // 0011 + auto boxBody = box->getPhysicsBody(); + boxBody->setVelocity(velocity); + boxBody->setCategoryBitmask(0x01); // 0001 + boxBody->setContactTestBitmask(0x04); // 0100 + boxBody->setCollisionBitmask(0x03); // 0011 root->addChild(box); } @@ -1445,12 +1449,13 @@ void PhysicsContactTest::resetTest() position.x = position.x * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); - Vect velocity((CCRANDOM_0_1() - 0.5) * 200, (CCRANDOM_0_1() - 0.5) * 200); + Vec2 velocity((CCRANDOM_0_1() - 0.5) * 200, (CCRANDOM_0_1() - 0.5) * 200); auto box = makeBox(position, size, 2, PhysicsMaterial(0.1f, 1, 0.0f)); - box->getComponent()->getPhysicsBody()->setVelocity(velocity); - box->getComponent()->getPhysicsBody()->setCategoryBitmask(0x02); // 0010 - box->getComponent()->getPhysicsBody()->setContactTestBitmask(0x08); // 1000 - box->getComponent()->getPhysicsBody()->setCollisionBitmask(0x01); // 0001 + auto boxBody = box->getPhysicsBody(); + boxBody->setVelocity(velocity); + boxBody->setCategoryBitmask(0x02); // 0010 + boxBody->setContactTestBitmask(0x08); // 1000 + boxBody->setCollisionBitmask(0x01); // 0001 root->addChild(box); } @@ -1463,12 +1468,13 @@ void PhysicsContactTest::resetTest() position.x = position.x * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); - Vect velocity((CCRANDOM_0_1() - 0.5) * 300, (CCRANDOM_0_1() - 0.5) * 300); + Vec2 velocity((CCRANDOM_0_1() - 0.5) * 300, (CCRANDOM_0_1() - 0.5) * 300); auto triangle = makeTriangle(position, size, 1, PhysicsMaterial(0.1f, 1, 0.0f)); - triangle->getComponent()->getPhysicsBody()->setVelocity(velocity); - triangle->getComponent()->getPhysicsBody()->setCategoryBitmask(0x04); // 0100 - triangle->getComponent()->getPhysicsBody()->setContactTestBitmask(0x01); // 0001 - triangle->getComponent()->getPhysicsBody()->setCollisionBitmask(0x06); // 0110 + auto triangleBody = triangle->getPhysicsBody(); + triangleBody->setVelocity(velocity); + triangleBody->setCategoryBitmask(0x04); // 0100 + triangleBody->setContactTestBitmask(0x01); // 0001 + triangleBody->setCollisionBitmask(0x06); // 0110 root->addChild(triangle); } @@ -1481,12 +1487,13 @@ void PhysicsContactTest::resetTest() position.x = position.x * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); - Vect velocity((CCRANDOM_0_1() - 0.5) * 300, (CCRANDOM_0_1() - 0.5) * 300); + Vec2 velocity((CCRANDOM_0_1() - 0.5) * 300, (CCRANDOM_0_1() - 0.5) * 300); auto triangle = makeTriangle(position, size, 2, PhysicsMaterial(0.1f, 1, 0.0f)); - triangle->getComponent()->getPhysicsBody()->setVelocity(velocity); - triangle->getComponent()->getPhysicsBody()->setCategoryBitmask(0x08); // 1000 - triangle->getComponent()->getPhysicsBody()->setContactTestBitmask(0x02); // 0010 - triangle->getComponent()->getPhysicsBody()->setCollisionBitmask(0x01); // 0001 + auto triangleBody = triangle->getPhysicsBody(); + triangleBody->setVelocity(velocity); + triangleBody->setCategoryBitmask(0x08); // 1000 + triangleBody->setContactTestBitmask(0x02); // 0010 + triangleBody->setCollisionBitmask(0x01); // 0001 root->addChild(triangle); } } @@ -1525,7 +1532,7 @@ void PhysicsPositionRotationTest::onEnter() _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto wall = Node::create(); - addPhysicsComponent(wall, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + wall->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); wall->setPosition(VisibleRect::center()); addChild(wall); @@ -1534,32 +1541,33 @@ void PhysicsPositionRotationTest::onEnter() //anchorNode->setAnchorPoint(Vec2(0.1f, 0.9f)); anchorNode->setPosition(100, 100); anchorNode->setScale(0.25); - addPhysicsComponent(anchorNode, PhysicsBody::createBox(anchorNode->getContentSize())); - anchorNode->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + anchorNode->addComponent(PhysicsBody::createBox(anchorNode->getContentSize())); + anchorNode->getPhysicsBody()->setTag(DRAG_BODYS_TAG); addChild(anchorNode); //parent test auto parent = Sprite::create("Images/YellowSquare.png"); parent->setPosition(200, 100); parent->setScale(0.25); - addPhysicsComponent(parent,PhysicsBody::createBox(parent->getContentSize())); - parent->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + parent->addComponent(PhysicsBody::createBox(parent->getContentSize())); + parent->getPhysicsBody()->setTag(DRAG_BODYS_TAG); addChild(parent); auto leftBall = Sprite::create("Images/ball.png"); leftBall->setPosition(-30, 0); leftBall->Node::setScale(2); - addPhysicsComponent(leftBall, PhysicsBody::createCircle(leftBall->getContentSize().width/2)); - leftBall->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + leftBall->addComponent(PhysicsBody::createCircle(leftBall->getContentSize().width/2)); + leftBall->getPhysicsBody()->setTag(DRAG_BODYS_TAG); parent->addChild(leftBall); // offset position rotation test auto offsetPosNode = Sprite::create("Images/YellowSquare.png"); offsetPosNode->setPosition(100, 200); - addPhysicsComponent(offsetPosNode, PhysicsBody::createBox(offsetPosNode->getContentSize()/2)); - offsetPosNode->getComponent()->getPhysicsBody()->setPositionOffset(-Vec2(offsetPosNode->getContentSize() / 2)); - offsetPosNode->getComponent()->getPhysicsBody()->setRotationOffset(45); - offsetPosNode->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto body = PhysicsBody::createBox(offsetPosNode->getContentSize() / 2); + offsetPosNode->addComponent(body); + body->setPositionOffset(-Vec2(offsetPosNode->getContentSize() / 2)); + body->setRotationOffset(45); + body->setTag(DRAG_BODYS_TAG); addChild(offsetPosNode); return; @@ -1582,36 +1590,39 @@ void PhysicsSetGravityEnableTest::onEnter() // wall auto wall = Node::create(); - addPhysicsComponent(wall, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1.0f, 0.0f))); + wall->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1.0f, 0.0f))); wall->setPosition(VisibleRect::center()); addChild(wall); // common box auto commonBox = makeBox(Vec2(100, 100), Size(50, 50), 1); - commonBox->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + commonBox->getPhysicsBody()->setTag(DRAG_BODYS_TAG); addChild(commonBox); auto box = makeBox(Vec2(200, 100), Size(50, 50), 2); - box->getComponent()->getPhysicsBody()->setMass(20); - box->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - box->getComponent()->getPhysicsBody()->setGravityEnable(false); + auto boxBody = box->getPhysicsBody(); + boxBody->setMass(20); + boxBody->setTag(DRAG_BODYS_TAG); + boxBody->setGravityEnable(false); addChild(box); auto ball = makeBall(Vec2(200, 200), 50); ball->setTag(2); - ball->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - ball->getComponent()->getPhysicsBody()->setGravityEnable(false); + auto ballBody = ball->getPhysicsBody(); + ballBody->setTag(DRAG_BODYS_TAG); + ballBody->setGravityEnable(false); + ballBody->setMass(50); addChild(ball); - ball->getComponent()->getPhysicsBody()->setMass(50); + scheduleOnce(CC_SCHEDULE_SELECTOR(PhysicsSetGravityEnableTest::onScheduleOnce), 1.0); } void PhysicsSetGravityEnableTest::onScheduleOnce(float delta) { auto ball = getChildByTag(2); - ball->getComponent()->getPhysicsBody()->setMass(200); + ball->getPhysicsBody()->setMass(200); - _physicsWorld->setGravity(Vect(0, 98)); + _physicsWorld->setGravity(Vec2(0, 98)); } std::string PhysicsSetGravityEnableTest::title() const @@ -1640,7 +1651,7 @@ void PhysicsDemoBug5482::onEnter() // wall auto wall = Node::create(); - addPhysicsComponent(wall, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1.0f, 0.0f))); + wall->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1.0f, 0.0f))); wall->setPosition(VisibleRect::center()); addChild(wall); @@ -1653,12 +1664,10 @@ void PhysicsDemoBug5482::onEnter() _nodeA = Sprite::create("Images/YellowSquare.png"); _nodeA->setPosition(VisibleRect::center().x - 150, 100); - _nodeA->addComponent(ComponentPhysics2d::create()); this->addChild(_nodeA); _nodeB = Sprite::create("Images/YellowSquare.png"); _nodeB->setPosition(VisibleRect::center().x + 150, 100); - _nodeB->addComponent(ComponentPhysics2d::create()); this->addChild(_nodeB); _body = PhysicsBody::createBox(_nodeA->getContentSize()); @@ -1675,7 +1684,11 @@ void PhysicsDemoBug5482::onExit() void PhysicsDemoBug5482::changeBodyCallback(Ref* sender) { Sprite* node = _bodyInA ? _nodeB : _nodeA; - node->getComponent()->setPhysicsBody(_body); + if (_body->getOwner()) + { + _body->getOwner()->removeComponent(_body); + } + node->addComponent(_body); _bodyInA = !_bodyInA; } @@ -1698,7 +1711,7 @@ void PhysicsFixedUpdate::onEnter() // wall auto wall = Node::create(); - addPhysicsComponent(wall, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1, 0.0f))); + wall->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1, 0.0f))); wall->setPosition(VisibleRect::center()); this->addChild(wall); @@ -1711,9 +1724,10 @@ void PhysicsFixedUpdate::addBall() { auto ball = Sprite::create("Images/ball.png"); ball->setPosition(100, 100); - addPhysicsComponent(ball, PhysicsBody::createCircle(ball->getContentSize().width/2, PhysicsMaterial(0.1f, 1, 0.0f))); - ball->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - ball->getComponent()->getPhysicsBody()->setVelocity(Point(1000, 20)); + auto ballBody = PhysicsBody::createCircle(ball->getContentSize().width / 2, PhysicsMaterial(0.1f, 1, 0.0f)); + ball->addComponent(ballBody); + ballBody->setTag(DRAG_BODYS_TAG); + ballBody->setVelocity(Point(1000, 20)); this->addChild(ball); } @@ -1765,7 +1779,7 @@ void PhysicsTransformTest::onEnter() addChild(_rootLayer); auto wall = Node::create(); - addPhysicsComponent(wall, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1.0f, 0.0f))); + wall->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1.0f, 0.0f))); wall->setPosition(VisibleRect::center()); _rootLayer->addChild(wall); @@ -1773,16 +1787,16 @@ void PhysicsTransformTest::onEnter() _parentSprite = Sprite::create("Images/YellowSquare.png"); _parentSprite->setPosition(200, 100); _parentSprite->setScale(0.25); - addPhysicsComponent(_parentSprite, PhysicsBody::createBox(_parentSprite->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f))); - _parentSprite->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + _parentSprite->addComponent(PhysicsBody::createBox(_parentSprite->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f))); + _parentSprite->getPhysicsBody()->setTag(DRAG_BODYS_TAG); _parentSprite->setTag(1); _rootLayer->addChild(_parentSprite); auto leftBall = Sprite::create("Images/ball.png"); leftBall->setPosition(-30, 0); leftBall->setScale(2); - addPhysicsComponent(leftBall, PhysicsBody::createCircle(leftBall->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f))); - leftBall->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + leftBall->addComponent(PhysicsBody::createCircle(leftBall->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f))); + leftBall->getPhysicsBody()->setTag(DRAG_BODYS_TAG); _parentSprite->addChild(leftBall); ScaleTo* scaleTo = ScaleTo::create(2.0, 0.5); @@ -1792,14 +1806,14 @@ void PhysicsTransformTest::onEnter() auto normal = Sprite::create("Images/YellowSquare.png"); normal->setPosition(300, 100); normal->setScale(0.25, 0.5); - addPhysicsComponent(normal,PhysicsBody::createBox(normal->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f))); - normal->getComponent()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + normal->addComponent(PhysicsBody::createBox(normal->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f))); + normal->getPhysicsBody()->setTag(DRAG_BODYS_TAG); _rootLayer->addChild(normal); auto bullet = Sprite::create("Images/ball.png"); bullet->setPosition(200, 200); - addPhysicsComponent(bullet,PhysicsBody::createCircle(bullet->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f))); - bullet->getComponent()->getPhysicsBody()->setVelocity(Vect(100, 100)); + bullet->addComponent(PhysicsBody::createCircle(bullet->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f))); + bullet->getPhysicsBody()->setVelocity(Vec2(100, 100)); _rootLayer->addChild(bullet); MoveBy* move = MoveBy::create(2.0f, Vec2(100, 100)); diff --git a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h index 4163e1d13b..7872a7aff4 100644 --- a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h +++ b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.h @@ -33,7 +33,6 @@ public: void toggleDebug(); protected: - void addPhysicsComponent(cocos2d::Node *node, cocos2d::PhysicsBody *physicsBody); cocos2d::Texture2D* _spriteTexture; cocos2d::SpriteBatchNode* _ball; diff --git a/tests/lua-tests/src/PhysicsTest/PhysicsTest.lua b/tests/lua-tests/src/PhysicsTest/PhysicsTest.lua index 54bcb41b9a..919e7a5d9e 100644 --- a/tests/lua-tests/src/PhysicsTest/PhysicsTest.lua +++ b/tests/lua-tests/src/PhysicsTest/PhysicsTest.lua @@ -3,7 +3,6 @@ local MATERIAL_DEFAULT = cc.PhysicsMaterial(0.1, 0.5, 0.5) local curLayer = nil local STATIC_COLOR = cc.c4f(1.0, 0.0, 0.0, 1.0) local DRAG_BODYS_TAG = 0x80 -local PHYSICS_COMPONENT_NAME = "physics_component" local function range(from, to, step) step = step or 1 @@ -44,12 +43,6 @@ local function initWithLayer(layer, callback) layer:registerScriptHandler(onNodeEvent) end -local function addPhysicsComponent(node, physicsBody) - local component = cc.ComponentPhysics2d:create(physicsBody) - component:setName(PHYSICS_COMPONENT_NAME) - node:addComponent(component) -end - local function addGrossiniAtPosition(layer, p, scale) scale = scale or 1.0 @@ -60,8 +53,7 @@ local function addGrossiniAtPosition(layer, p, scale) local sp = cc.Sprite:createWithTexture(layer.spriteTexture, cc.rect(posx, posy, 85, 121)) sp:setScale(scale) - -- sp:setPhysicsBody(cc.PhysicsBody:createBox(cc.size(48.0*scale, 108.0*scale))) - addPhysicsComponent(sp, cc.PhysicsBody:createBox(cc.size(48.0, 108.0))) + sp:setPhysicsBody(cc.PhysicsBody:createBox(cc.size(48.0*scale, 108.0*scale))) layer:addChild(sp) sp:setPosition(p) return sp @@ -82,7 +74,7 @@ local function onTouchBegan(touch, event) if body then local mouse = cc.Node:create() local physicsBody = cc.PhysicsBody:create(PHYSICS_INFINITY, PHYSICS_INFINITY) - addPhysicsComponent(mouse, physicsBody) + mouse:setPhysicsBody(physicsBody) physicsBody:setDynamic(false) mouse:setPosition(location) curLayer:addChild(mouse) @@ -123,8 +115,7 @@ local function makeBall(layer, point, radius, material) ball:setScale(0.13 * radius) local body = cc.PhysicsBody:createCircle(ball:getContentSize().width / 2, material) - -- ball:setPhysicsBody(body) - addPhysicsComponent(ball, body) + ball:setPhysicsBody(body) ball:setPosition(point) return ball @@ -146,7 +137,7 @@ local function makeBox(point, size, color, material) box:setScaleY(size.height/100.0) local body = cc.PhysicsBody:createBox(box:getContentSize(), material) - addPhysicsComponent(box, body) + box:setPhysicsBody(body) box:setPosition(cc.p(point.x, point.y)) return box @@ -176,7 +167,7 @@ local function makeTriangle(point, size, color, material) } local body = cc.PhysicsBody:createPolygon(vers, material) - addPhysicsComponent(triangle, body) + triangle:setPhysicsBody(body) triangle:setPosition(point) return triangle @@ -199,8 +190,7 @@ local function PhysicsDemoClickAdd() addGrossiniAtPosition(layer, VisibleRect:center()) local node = cc.Node:create() - addPhysicsComponent(node, - cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, + node:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, VisibleRect:getVisibleRect().height ) ) @@ -278,7 +268,7 @@ local function PhysicsDemoLogoSmash() 2*(logo_height-y + y_jitter) + VisibleRect:getVisibleRect().height/2 - logo_height/2), 0.95, cc.PhysicsMaterial(0.01, 0.0, 0.0)) - local physicsBody = ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local physicsBody = ball:getPhysicsBody() physicsBody:setMass(1.0) physicsBody:setMoment(PHYSICS_INFINITY) @@ -289,7 +279,7 @@ local function PhysicsDemoLogoSmash() local bullet = makeBall(layer, cc.p(400, 0), 10, cc.PhysicsMaterial(PHYSICS_INFINITY, 0, 0)) - bullet:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setVelocity(cc.p(200, 0)) + bullet:getPhysicsBody():setVelocity(cc.p(200, 0)) bullet:setPosition(cc.p(-500, VisibleRect:getVisibleRect().height/2)) layer.ball:addChild(bullet) end @@ -317,7 +307,7 @@ local function PhysicsDemoJoints() local node = cc.Node:create() local box = cc.PhysicsBody:create() - addPhysicsComponent(node, box) + node:setPhysicsBody(box) box:setDynamic(false) node:setPosition(cc.p(0, 0)) layer:addChild(node) @@ -336,11 +326,11 @@ local function PhysicsDemoJoints() if index == 0 then local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBall(layer, cc.p(offset.x + 30, offset.y), 10) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) local joint = cc.PhysicsJointPin:construct(sp1PhysicsBody, sp2PhysicsBody, offset) @@ -350,11 +340,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 1 then local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) local joint = cc.PhysicsJointFixed:construct(sp1PhysicsBody, sp2PhysicsBody, offset) @@ -364,11 +354,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 2 then local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) local joint = cc.PhysicsJointDistance:construct(sp1PhysicsBody, @@ -381,11 +371,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 3 then local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) local joint = cc.PhysicsJointLimit:construct(sp1PhysicsBody, @@ -400,11 +390,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 4 then local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) local joint = cc.PhysicsJointSpring:construct(sp1PhysicsBody, @@ -419,11 +409,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 5 then local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) local joint = cc.PhysicsJointGroove:construct(sp1PhysicsBody, @@ -437,11 +427,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 6 then local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, @@ -460,11 +450,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 7 then local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, @@ -483,11 +473,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 8 then local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, @@ -506,11 +496,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 9 then local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, @@ -526,11 +516,11 @@ local function PhysicsDemoJoints() layer:addChild(sp2) elseif index == 10 then local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) - local sp1PhysicsBody = sp1:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp1PhysicsBody = sp1:getPhysicsBody() sp1PhysicsBody:setTag(DRAG_BODYS_TAG) local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) - local sp2PhysicsBody = sp2:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local sp2PhysicsBody = sp2:getPhysicsBody() sp2PhysicsBody:setTag(DRAG_BODYS_TAG) scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, @@ -566,8 +556,7 @@ local function PhysicsDemoPyramidStack() eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) local node = cc.Node:create() - addPhysicsComponent(node, - cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, + node:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, VisibleRect:leftBottom().y + 50), cc.p(VisibleRect:rightBottom().x, VisibleRect:rightBottom().y + 50))) @@ -575,8 +564,8 @@ local function PhysicsDemoPyramidStack() local ball = cc.Sprite:create("Images/ball.png") ball:setScale(1) - addPhysicsComponent(ball, cc.PhysicsBody:createCircle(10)) - ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + ball:setPhysicsBody(cc.PhysicsBody:createCircle(10)) + ball:getPhysicsBody():setTag(DRAG_BODYS_TAG) ball:setPosition(cc.p(VisibleRect:bottom().x, VisibleRect:bottom().y + 60)) layer:addChild(ball) @@ -588,7 +577,7 @@ local function PhysicsDemoPyramidStack() local x = VisibleRect:bottom().x + (i/2 - j) * 11 local y = VisibleRect:bottom().y + (14 - i) * 23 + 100 local sp = addGrossiniAtPosition(layer, cc.p(x, y), 0.2) - sp:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + sp:getPhysicsBody():setTag(DRAG_BODYS_TAG) end end end @@ -625,8 +614,7 @@ local function PhysicsDemoRayCast() cc.Director:getInstance():getRunningScene():getPhysicsWorld():setGravity(cc.p(0,0)) local node = cc.DrawNode:create() - addPhysicsComponent(node, - cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, + node:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, VisibleRect:leftBottom().y + 50), cc.p(VisibleRect:rightBottom().x, VisibleRect:rightBottom().y + 50))) @@ -742,21 +730,20 @@ local function PhysicsDemoOneWayPlatform() eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) local ground = cc.Node:create() - addPhysicsComponent(ground, - cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, + ground:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, VisibleRect:leftBottom().y + 50), cc.p(VisibleRect:rightBottom().x, VisibleRect:rightBottom().y + 50))) layer:addChild(ground) local platform = makeBox(VisibleRect:center(), cc.size(200, 50)) - local platformPhysicsBody = platform:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local platformPhysicsBody = platform:getPhysicsBody() platformPhysicsBody:setDynamic(false) platformPhysicsBody:setContactTestBitmask(0xFFFFFFFF) layer:addChild(platform) local ball = makeBall(layer, cc.p(VisibleRect:center().x, VisibleRect:center().y - 50), 20) - local ballPhysicsBody = ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local ballPhysicsBody = ball:getPhysicsBody() ballPhysicsBody:setVelocity(cc.p(0, 150)) ballPhysicsBody:setTag(DRAG_BODYS_TAG) ballPhysicsBody:setMass(1.0) @@ -788,8 +775,7 @@ local function PhysicsDemoActions() eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) local node = cc.Node:create() - addPhysicsComponent(node, - cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, + node:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, VisibleRect:getVisibleRect().height))) node:setPosition(VisibleRect:center()) layer:addChild(node) @@ -798,7 +784,7 @@ local function PhysicsDemoActions() local sp2 = addGrossiniAtPosition(layer, cc.p(VisibleRect:left().x + 50, VisibleRect:left().y)) local sp3 = addGrossiniAtPosition(layer, cc.p(VisibleRect:right().x - 20, VisibleRect:right().y)) local sp4 = addGrossiniAtPosition(layer, cc.p(VisibleRect:leftTop().x + 50, VisibleRect:leftTop().y-50)) - sp4:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setGravityEnable(false) + sp4:getPhysicsBody():setGravityEnable(false) local actionTo = cc.JumpTo:create(2, cc.p(100,100), 50, 4) @@ -930,11 +916,11 @@ local function PhysicsDemoPump() VisibleRect:leftTop().y), 22, cc.PhysicsMaterial(0.05, 0.0, 0.1)) - ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + ball:getPhysicsBody():setTag(DRAG_BODYS_TAG) layer:addChild(ball) end - addPhysicsComponent(node, body) + node:setPhysicsBody(body) layer:addChild(node) local vec = @@ -950,7 +936,7 @@ local function PhysicsDemoPump() -- small gear local sgear = cc.Node:create() local sgearB = cc.PhysicsBody:createCircle(44) - addPhysicsComponent(sgear, sgearB) + sgear:setPhysicsBody(sgearB) sgear:setPosition(cc.p(VisibleRect:leftBottom().x + 125, VisibleRect:leftBottom().y)) layer:addChild(sgear) sgearB:setCategoryBitmask(4) @@ -962,7 +948,7 @@ local function PhysicsDemoPump() -- big gear local bgear = cc.Node:create() local bgearB = cc.PhysicsBody:createCircle(100) - addPhysicsComponent(bgear, bgearB) + bgear:setPhysicsBody(bgearB) bgear:setPosition(cc.p(VisibleRect:leftBottom().x + 275, VisibleRect:leftBottom().y)) layer:addChild(bgear) bgearB:setCategoryBitmask(4) @@ -976,7 +962,7 @@ local function PhysicsDemoPump() local pumpB = cc.PhysicsBody:createPolygon(vec, cc.PHYSICSBODY_MATERIAL_DEFAULT, cc.p(-center.x, -center.y)) - addPhysicsComponent(pump, pumpB) + pump:setPhysicsBody(pumpB) layer:addChild(pump) pumpB:setCategoryBitmask(2) pumpB:setGravityEnable(false) @@ -996,7 +982,7 @@ local function PhysicsDemoPump() pluggerB:setDynamic(true) pluggerB:setMass(30) pluggerB:setMoment(100000) - addPhysicsComponent(plugger, pluggerB) + plugger:setPhysicsBody(pluggerB) plugger:setPosition(segCenter) layer:addChild(plugger) pluggerB:setCategoryBitmask(2) @@ -1054,7 +1040,7 @@ local function PhysicsDemoSlice() cc.PHYSICSBODY_MATERIAL_DEFAULT, cc.p(-center.x, -center.y)) node:setPosition(center) - addPhysicsComponent(node, polyon) + node:setPhysicsBody(polyon) polyon:setVelocity(body:getVelocityAtWorldPoint(center)) polyon:setAngularVelocity(body:getAngularVelocity()) polyon.tag = sliceTag @@ -1093,8 +1079,7 @@ local function PhysicsDemoSlice() eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) local ground = cc.Node:create() - addPhysicsComponent(ground, - cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, + ground:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, VisibleRect:leftBottom().y + 50), cc.p(VisibleRect:rightBottom().x, VisibleRect:rightBottom().y + 50))) @@ -1102,9 +1087,9 @@ local function PhysicsDemoSlice() local box = cc.Node:create() local points = {cc.p(-100, -100), cc.p(-100, 100), cc.p(100, 100), cc.p(100, -100)} - addPhysicsComponent(box, cc.PhysicsBody:createPolygon(points)) + box:setPhysicsBody(cc.PhysicsBody:createPolygon(points)) box:setPosition(VisibleRect:center()) - box:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody().tag = sliceTag + box:getPhysicsBody().tag = sliceTag layer:addChild(box) end @@ -1191,7 +1176,7 @@ local function PhysicsContactTest() label:setPosition(cc.p(s.width/2, s.height-170)) local wall = cc.Node:create() - addPhysicsComponent(wall, cc.PhysicsBody:createEdgeBox(s, cc.PhysicsMaterial(0.1, 1, 0.0))) + wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(s, cc.PhysicsMaterial(0.1, 1, 0.0))) wall:setPosition(VisibleRect:center()) root:addChild(wall) @@ -1207,7 +1192,7 @@ local function PhysicsContactTest() VisibleRect:leftBottom().y + position.y + size.height/2) local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) local box = makeBox(position, size, 1, cc.PhysicsMaterial(0.1, 1, 0.0)) - local boxPhysicsBody = box:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local boxPhysicsBody = box:getPhysicsBody() boxPhysicsBody:setVelocity(velocity) boxPhysicsBody:setCategoryBitmask(1) -- 0001 boxPhysicsBody:setContactTestBitmask(4) -- 0100 @@ -1226,7 +1211,7 @@ local function PhysicsContactTest() VisibleRect:leftBottom().y + position.y + size.height/2) local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) local box = makeBox(position, size, 2, cc.PhysicsMaterial(0.1, 1, 0.0)) - local boxPhysicsBody = box:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local boxPhysicsBody = box:getPhysicsBody() boxPhysicsBody:setVelocity(velocity) boxPhysicsBody:setCategoryBitmask(2) -- 0010 boxPhysicsBody:setContactTestBitmask(8) -- 1000 @@ -1246,7 +1231,7 @@ local function PhysicsContactTest() VisibleRect:leftBottom().y + position.y + size.height/2) local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) local triangle = makeTriangle(position, size, 1, cc.PhysicsMaterial(0.1, 1, 0.0)) - local trianglePhysicsBody = triangle:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local trianglePhysicsBody = triangle:getPhysicsBody() trianglePhysicsBody:setVelocity(velocity) trianglePhysicsBody:setCategoryBitmask(4) -- 0100 trianglePhysicsBody:setContactTestBitmask(1) -- 0001 @@ -1266,7 +1251,7 @@ local function PhysicsContactTest() VisibleRect:leftBottom().y + position.y + size.height/2) local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) local triangle = makeTriangle(position, size, 2, cc.PhysicsMaterial(0.1, 1, 0.0)) - local trianglePhysicsBody = triangle:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local trianglePhysicsBody = triangle:getPhysicsBody() trianglePhysicsBody:setVelocity(velocity) trianglePhysicsBody:setCategoryBitmask(8) -- 1000 trianglePhysicsBody:setContactTestBitmask(2) -- 0010 @@ -1410,8 +1395,7 @@ local function PhysicsPositionRotationTest() eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) local wall = cc.Node:create() - addPhysicsComponent(wall, - cc.PhysicsBody:createEdgeBox(VisibleRect:getVisibleRect())) + wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(VisibleRect:getVisibleRect())) wall:setPosition(VisibleRect:center()) layer:addChild(wall) @@ -1420,9 +1404,8 @@ local function PhysicsPositionRotationTest() anchorNode:setAnchorPoint(cc.p(0.1, 0.9)) anchorNode:setPosition(100, 100) anchorNode:setScale(0.25) - addPhysicsComponent(anchorNode, - cc.PhysicsBody:createBox(anchorNode:getContentSize())) - anchorNode:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + anchorNode:setPhysicsBody(cc.PhysicsBody:createBox(anchorNode:getContentSize())) + anchorNode:getPhysicsBody():setTag(DRAG_BODYS_TAG) layer:addChild(anchorNode) --parent test @@ -1430,15 +1413,15 @@ local function PhysicsPositionRotationTest() parent:setPosition(200, 100) parent:setScale(0.25) local parentPhysicsBody = cc.PhysicsBody:createBox(anchorNode:getContentSize()) - addPhysicsComponent(parent, parentPhysicsBody) + parent:setPhysicsBody(parentPhysicsBody) parentPhysicsBody:setTag(DRAG_BODYS_TAG) layer:addChild(parent) local leftBall = cc.Sprite:create("Images/ball.png") leftBall:setPosition(-30, 0) leftBall:setScale(2) - addPhysicsComponent(leftBall, cc.PhysicsBody:createCircle(leftBall:getContentSize().width / 2)) - leftBall:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + leftBall:setPhysicsBody(cc.PhysicsBody:createCircle(leftBall:getContentSize().width / 2)) + leftBall:getPhysicsBody():setTag(DRAG_BODYS_TAG) parent:addChild(leftBall) -- offset position rotation test @@ -1446,7 +1429,7 @@ local function PhysicsPositionRotationTest() offsetPosNode:setPosition(100, 200) local offsetPosNodePhysicsBody = cc.PhysicsBody:createBox(cc.size(offsetPosNode:getContentSize().width/2, offsetPosNode:getContentSize().height/2)) - addPhysicsComponent(offsetPosNode, offsetPosNodePhysicsBody) + offsetPosNode:setPhysicsBody(offsetPosNodePhysicsBody) offsetPosNodePhysicsBody:setPositionOffset(cc.p(-offsetPosNode:getContentSize().width/2, -offsetPosNode:getContentSize().height/2)) offsetPosNodePhysicsBody:setRotationOffset(45) @@ -1472,19 +1455,18 @@ local function PhysicsSetGravityEnableTest() eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) local wall = cc.Node:create() - addPhysicsComponent(wall, - cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, + wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, VisibleRect:getVisibleRect().height), cc.PhysicsMaterial(0.1, 1.0, 0.0))) wall:setPosition(VisibleRect:center()); layer:addChild(wall) local commonBox = makeBox(cc.p(100, 100), cc.size(50, 50), 1) - commonBox:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + commonBox:getPhysicsBody():setTag(DRAG_BODYS_TAG) layer:addChild(commonBox) local box = makeBox(cc.p(200, 100), cc.size(50, 50), 2) - local boxBody = box:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local boxBody = box:getPhysicsBody() boxBody:setMass(20) boxBody:setTag(DRAG_BODYS_TAG) boxBody:setGravityEnable(false) @@ -1492,7 +1474,7 @@ local function PhysicsSetGravityEnableTest() local ball = makeBall(layer,cc.p(200,200),50) ball:setTag(2) - local ballBody = ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() + local ballBody = ball:getPhysicsBody() ballBody:setTag(DRAG_BODYS_TAG) ballBody:setGravityEnable(false) ballBody:setMass(50) @@ -1501,7 +1483,7 @@ local function PhysicsSetGravityEnableTest() local function onScheduleOnce() cclog("onScheduleOnce") local ball = layer:getChildByTag(2) - ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setMass(200) + ball:getPhysicsBody():setMass(200) cc.Director:getInstance():getRunningScene():getPhysicsWorld():setGravity(cc.p(0, 98)) end --layer:scheduleOnce(onScheduleOnce,1.0) @@ -1531,8 +1513,7 @@ local function PhysicsDemoBug5482() -- wall local wall = cc.Node:create() - addPhysicsComponent(wall, - cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, + wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, VisibleRect:getVisibleRect().height), cc.PhysicsMaterial(0.1, 1.0, 0.0))) wall:setPosition(VisibleRect:center()); @@ -1540,12 +1521,12 @@ local function PhysicsDemoBug5482() local _nodeA = cc.Sprite:create("Images/YellowSquare.png") _nodeA:setPosition(cc.p(VisibleRect:center().x-150,100)) - addPhysicsComponent(_nodeA,nil) + _nodeA:setPhysicsBody(nil) layer:addChild(_nodeA) local _nodeB = cc.Sprite:create("Images/YellowSquare.png") _nodeB:setPosition(cc.p(VisibleRect:center().x+150,100)) - addPhysicsComponent(_nodeB,nil) + _nodeB:setPhysicsBody(nil) layer:addChild(_nodeB) local _body = cc.PhysicsBody:createBox(_nodeA:getContentSize()) @@ -1561,7 +1542,7 @@ local function PhysicsDemoBug5482() node = _nodeA cclog("_nodeA") end - node:getComponent(PHYSICS_COMPONENT_NAME):setPhysicsBody(_body) + node:setPhysicsBody(_body) _bodyInA = not _bodyInA end @@ -1588,9 +1569,9 @@ local function PhysicsDemoBug5482() local function addBall() local ball = cc.Sprite:create("Images/ball.png") ball:setPosition(cc.p(100,100)) - addPhysicsComponent(ball,cc.PhysicsBody:createCircle(ball:getContentSize().width/2, cc.PhysicsMaterial(0.1, 1, 0.0))) - ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) - ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setVelocity(cc.p(1000,20)) + ball:setPhysicsBody(cc.PhysicsBody:createCircle(ball:getContentSize().width/2, cc.PhysicsMaterial(0.1, 1, 0.0))) + ball:getPhysicsBody():setTag(DRAG_BODYS_TAG) + ball:getPhysicsBody():setVelocity(cc.p(1000,20)) layer:addChild(ball) end @@ -1608,8 +1589,7 @@ local function PhysicsDemoBug5482() -- wall local wall = cc.Node:create() - addPhysicsComponent(wall, - cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, + wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, VisibleRect:getVisibleRect().height), cc.PhysicsMaterial(0.1, 1.0, 0.0))) wall:setPosition(VisibleRect:center()); @@ -1642,8 +1622,7 @@ local function PhysicsTransformTest() layer:addChild(_rootLayer) local wall = cc.Node:create() - addPhysicsComponent(wall, - cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, + wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, VisibleRect:getVisibleRect().height), cc.PhysicsMaterial(0.1, 1.0, 0.0))) wall:setPosition(VisibleRect:center()); @@ -1652,16 +1631,16 @@ local function PhysicsTransformTest() local _parentSprite = cc.Sprite:create("Images/YellowSquare.png") _parentSprite:setPosition(cc.p(200,100)) _parentSprite:setScale(0.25) - addPhysicsComponent(_parentSprite,cc.PhysicsBody:createBox(_parentSprite:getContentSize(),cc.PhysicsMaterial(0.1, 1.0, 0.0))) - _parentSprite:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + _parentSprite:setPhysicsBody(cc.PhysicsBody:createBox(_parentSprite:getContentSize(),cc.PhysicsMaterial(0.1, 1.0, 0.0))) + _parentSprite:getPhysicsBody():setTag(DRAG_BODYS_TAG) _parentSprite:setTag(1) _rootLayer:addChild(_parentSprite) local leftBall = cc.Sprite:create("Images/ball.png") leftBall:setPosition(cc.p(-30,0)) leftBall:setScale(2) - addPhysicsComponent(leftBall,cc.PhysicsBody:createCircle(leftBall:getContentSize().width/2,cc.PhysicsMaterial(0.1,1.0,0.0))) - leftBall:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + leftBall:setPhysicsBody(cc.PhysicsBody:createCircle(leftBall:getContentSize().width/2,cc.PhysicsMaterial(0.1,1.0,0.0))) + leftBall:getPhysicsBody():setTag(DRAG_BODYS_TAG) _parentSprite:addChild(leftBall) local scaleTo = cc.ScaleTo:create(2.0,0.5) @@ -1671,14 +1650,14 @@ local function PhysicsTransformTest() local normal = cc.Sprite:create("Images/YellowSquare.png") normal:setPosition(cc.p(300,100)) normal:setScale(0.25,0.5) - addPhysicsComponent(normal,cc.PhysicsBody:createBox(normal:getContentSize()),cc.PhysicsMaterial(0.1,1.0,0.0)) - normal:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) + normal:setPhysicsBody(cc.PhysicsBody:createBox(normal:getContentSize()),cc.PhysicsMaterial(0.1,1.0,0.0)) + normal:getPhysicsBody():setTag(DRAG_BODYS_TAG) _rootLayer:addChild(normal) local bullet = cc.Sprite:create("Images/ball.png") bullet:setPosition(cc.p(200,200)) - addPhysicsComponent(bullet,cc.PhysicsBody:createCircle(bullet:getContentSize().width/2,cc.PhysicsMaterial(0.1,1.0,0.0))) - bullet:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setVelocity(cc.p(100,100)) + bullet:setPhysicsBody(cc.PhysicsBody:createCircle(bullet:getContentSize().width/2,cc.PhysicsMaterial(0.1,1.0,0.0))) + bullet:getPhysicsBody():setVelocity(cc.p(100,100)) _rootLayer:addChild(bullet) local move = cc.MoveBy:create(2.0,cc.p(100,100)) diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index 10c6bc303d..63ac9f4c32 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -35,7 +35,7 @@ classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* M # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. -skip = Node::[setGLServerState description getUserObject .*UserData getGLServerState .*schedule getPosition$ setContentSize setAnchorPoint enumerateChildren getonEnterTransitionDidFinishCallback getOnEnterCallback getOnExitCallback getonExitTransitionDidStartCallback setAdditionalTransform setRotationQuat getRotationQuat .*(Physics).*], +skip = Node::[setGLServerState description getUserObject .*UserData getGLServerState .*schedule getPosition$ setContentSize setAnchorPoint enumerateChildren getonEnterTransitionDidFinishCallback getOnEnterCallback getOnExitCallback getonExitTransitionDidStartCallback setAdditionalTransform setRotationQuat getRotationQuat], Sprite::[getQuad ^setPosition$ ^create$ setPolygonInfo initWithPolygon getPolygonInfo], SpriteBatchNode::[getDescendants], MotionStreak::[draw update], diff --git a/tools/tolua/cocos2dx_physics.ini b/tools/tolua/cocos2dx_physics.ini index ef1bede544..6a763b9d9d 100644 --- a/tools/tolua/cocos2dx_physics.ini +++ b/tools/tolua/cocos2dx_physics.ini @@ -29,7 +29,7 @@ headers = %(cocosdir)s/cocos/cocos2d.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = Event(.*(Physics).*) Physics.* ComponentPhysics2d +classes = Event(.*(Physics).*) Physics.* # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -46,9 +46,7 @@ skip = PhysicsBody::[getJoints createPolygon createEdgeChain createEdgePolygon], PhysicsShapeEdgePolygon::[create ^getPoints$], PhysicsShapeEdgeChain::[create ^getPoints$], PhysicsWorld::[getScene queryPoint queryRect rayCast], - PhysicsContact::[getData setData], - PhysicsManager::[PhysicsManager update], - ComponentPhysics2d::[beforeSimulation afterSimulation] + PhysicsContact::[getData setData] rename_functions =