Refine components to improve performance

This commit is contained in:
WenhaiLin 2015-09-18 11:48:43 +08:00
parent 05ecef730b
commit a17a702cd1
48 changed files with 822 additions and 1502 deletions

View File

@ -1884,14 +1884,6 @@
A045F6DD1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6DA1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp */; }; A045F6DD1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6DA1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp */; };
A045F6DE1BA816A1005076C7 /* CCCameraBackgroundBrush.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6DB1BA816A1005076C7 /* CCCameraBackgroundBrush.h */; }; A045F6DE1BA816A1005076C7 /* CCCameraBackgroundBrush.h in Headers */ = {isa = PBXBuildFile; fileRef = A045F6DB1BA816A1005076C7 /* CCCameraBackgroundBrush.h */; };
A045F6DF1BA816A1005076C7 /* 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 */; }; A045F6EF1BA81821005076C7 /* GameNode3DReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A045F6ED1BA81821005076C7 /* GameNode3DReader.cpp */; };
A045F6F01BA81821005076C7 /* 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 */; }; 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 = "<group>"; }; A045F6D51BA81577005076C7 /* CCTextureCube.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureCube.h; sourceTree = "<group>"; };
A045F6DA1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCCameraBackgroundBrush.cpp; sourceTree = "<group>"; }; A045F6DA1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCCameraBackgroundBrush.cpp; sourceTree = "<group>"; };
A045F6DB1BA816A1005076C7 /* CCCameraBackgroundBrush.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCCameraBackgroundBrush.h; sourceTree = "<group>"; }; A045F6DB1BA816A1005076C7 /* CCCameraBackgroundBrush.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCCameraBackgroundBrush.h; sourceTree = "<group>"; };
A045F6E01BA8170A005076C7 /* CCComponentPhysics2d.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCComponentPhysics2d.cpp; sourceTree = "<group>"; };
A045F6E11BA8170A005076C7 /* CCComponentPhysics2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCComponentPhysics2d.h; sourceTree = "<group>"; };
A045F6E21BA8170A005076C7 /* CCPhysicsManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCPhysicsManager.cpp; sourceTree = "<group>"; };
A045F6E31BA8170A005076C7 /* CCPhysicsManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCPhysicsManager.h; sourceTree = "<group>"; };
A045F6ED1BA81821005076C7 /* GameNode3DReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GameNode3DReader.cpp; sourceTree = "<group>"; }; A045F6ED1BA81821005076C7 /* GameNode3DReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GameNode3DReader.cpp; sourceTree = "<group>"; };
A045F6EE1BA81821005076C7 /* GameNode3DReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameNode3DReader.h; sourceTree = "<group>"; }; A045F6EE1BA81821005076C7 /* GameNode3DReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameNode3DReader.h; sourceTree = "<group>"; };
A0534A631B872FFD006B03E5 /* CCDownloader-apple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCDownloader-apple.h"; sourceTree = "<group>"; }; A0534A631B872FFD006B03E5 /* CCDownloader-apple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCDownloader-apple.h"; sourceTree = "<group>"; };
@ -7428,10 +7416,6 @@
46A170611807CE7A005B8026 /* physics */ = { 46A170611807CE7A005B8026 /* physics */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
A045F6E01BA8170A005076C7 /* CCComponentPhysics2d.cpp */,
A045F6E11BA8170A005076C7 /* CCComponentPhysics2d.h */,
A045F6E21BA8170A005076C7 /* CCPhysicsManager.cpp */,
A045F6E31BA8170A005076C7 /* CCPhysicsManager.h */,
ED74D7681A5B8A2600157FD4 /* CCPhysicsHelper.h */, ED74D7681A5B8A2600157FD4 /* CCPhysicsHelper.h */,
46A1706E1807CE7A005B8026 /* CCPhysicsBody.cpp */, 46A1706E1807CE7A005B8026 /* CCPhysicsBody.cpp */,
46A1706F1807CE7A005B8026 /* CCPhysicsBody.h */, 46A1706F1807CE7A005B8026 /* CCPhysicsBody.h */,
@ -9851,7 +9835,6 @@
15AE1A3519AAD3D500C27E9E /* b2EdgeShape.h in Headers */, 15AE1A3519AAD3D500C27E9E /* b2EdgeShape.h in Headers */,
B6CAB3151AF9AA1A00B9B856 /* btBoxCollision.h in Headers */, B6CAB3151AF9AA1A00B9B856 /* btBoxCollision.h in Headers */,
50643BD919BFAF4400EF68ED /* CCApplication.h in Headers */, 50643BD919BFAF4400EF68ED /* CCApplication.h in Headers */,
A045F6E61BA8170A005076C7 /* CCComponentPhysics2d.h in Headers */,
B665E3581AA80A6500DDB1C5 /* CCPUOnQuotaObserverTranslator.h in Headers */, B665E3581AA80A6500DDB1C5 /* CCPUOnQuotaObserverTranslator.h in Headers */,
B6CAB2371AF9AA1A00B9B856 /* btCompoundCollisionAlgorithm.h in Headers */, B6CAB2371AF9AA1A00B9B856 /* btCompoundCollisionAlgorithm.h in Headers */,
B665E3DC1AA80A6600DDB1C5 /* CCPUScriptTranslator.h in Headers */, B665E3DC1AA80A6600DDB1C5 /* CCPUScriptTranslator.h in Headers */,
@ -10023,7 +10006,6 @@
B6CAB5331AF9AA1A00B9B856 /* btTransformUtil.h in Headers */, B6CAB5331AF9AA1A00B9B856 /* btTransformUtil.h in Headers */,
B6DD2FEF1B04825B00E47F5F /* DetourTileCache.h in Headers */, B6DD2FEF1B04825B00E47F5F /* DetourTileCache.h in Headers */,
50ABBECD1925AB6F00A911A9 /* s3tc.h in Headers */, 50ABBECD1925AB6F00A911A9 /* s3tc.h in Headers */,
A045F6EA1BA8170A005076C7 /* CCPhysicsManager.h in Headers */,
B6CAB3651AF9AA1A00B9B856 /* btContinuousConvexCollision.h in Headers */, B6CAB3651AF9AA1A00B9B856 /* btContinuousConvexCollision.h in Headers */,
15AE1BD119AAE01E00C27E9E /* CCControlHuePicker.h in Headers */, 15AE1BD119AAE01E00C27E9E /* CCControlHuePicker.h in Headers */,
B5CE6DC01B3BF2B1002B0419 /* UIAbstractCheckButton.h in Headers */, B5CE6DC01B3BF2B1002B0419 /* UIAbstractCheckButton.h in Headers */,
@ -10520,7 +10502,6 @@
15AE1A9C19AAD40300C27E9E /* b2Settings.h in Headers */, 15AE1A9C19AAD40300C27E9E /* b2Settings.h in Headers */,
1A5701FA180BCBAD0088DEC7 /* CCMenu.h in Headers */, 1A5701FA180BCBAD0088DEC7 /* CCMenu.h in Headers */,
15AE18BA19AAD33D00C27E9E /* CCControlButtonLoader.h in Headers */, 15AE18BA19AAD33D00C27E9E /* CCControlButtonLoader.h in Headers */,
A045F6EB1BA8170A005076C7 /* CCPhysicsManager.h in Headers */,
1A5701FE180BCBAD0088DEC7 /* CCMenuItem.h in Headers */, 1A5701FE180BCBAD0088DEC7 /* CCMenuItem.h in Headers */,
50ABC00C1926664800A911A9 /* CCDevice.h in Headers */, 50ABC00C1926664800A911A9 /* CCDevice.h in Headers */,
1A570205180BCBD40088DEC7 /* CCClippingNode.h in Headers */, 1A570205180BCBD40088DEC7 /* CCClippingNode.h in Headers */,
@ -10920,7 +10901,6 @@
15AE195A19AAD35100C27E9E /* CCProcessBase.h in Headers */, 15AE195A19AAD35100C27E9E /* CCProcessBase.h in Headers */,
15AE193D19AAD35100C27E9E /* CCArmatureDefine.h in Headers */, 15AE193D19AAD35100C27E9E /* CCArmatureDefine.h in Headers */,
B6CAB37A1AF9AA1A00B9B856 /* btGjkEpaPenetrationDepthSolver.h in Headers */, B6CAB37A1AF9AA1A00B9B856 /* btGjkEpaPenetrationDepthSolver.h in Headers */,
A045F6E71BA8170A005076C7 /* CCComponentPhysics2d.h in Headers */,
B6CAB21A1AF9AA1A00B9B856 /* btBox2dBox2dCollisionAlgorithm.h in Headers */, B6CAB21A1AF9AA1A00B9B856 /* btBox2dBox2dCollisionAlgorithm.h in Headers */,
382384041A259005002C4610 /* CSParseBinary_generated.h in Headers */, 382384041A259005002C4610 /* CSParseBinary_generated.h in Headers */,
B6CAB5401AF9AA1A00B9B856 /* cl_platform.h in Headers */, B6CAB5401AF9AA1A00B9B856 /* cl_platform.h in Headers */,
@ -11211,7 +11191,6 @@
B665E2621AA80A6500DDB1C5 /* CCPUDoExpireEventHandler.cpp in Sources */, B665E2621AA80A6500DDB1C5 /* CCPUDoExpireEventHandler.cpp in Sources */,
B665E4161AA80A6600DDB1C5 /* CCPUTextureAnimatorTranslator.cpp in Sources */, B665E4161AA80A6600DDB1C5 /* CCPUTextureAnimatorTranslator.cpp in Sources */,
B665E41E1AA80A6600DDB1C5 /* CCPUTextureRotatorTranslator.cpp in Sources */, B665E41E1AA80A6600DDB1C5 /* CCPUTextureRotatorTranslator.cpp in Sources */,
A045F6E81BA8170A005076C7 /* CCPhysicsManager.cpp in Sources */,
15AE189819AAD33D00C27E9E /* CCMenuItemLoader.cpp in Sources */, 15AE189819AAD33D00C27E9E /* CCMenuItemLoader.cpp in Sources */,
15AE1A5719AAD40300C27E9E /* b2Settings.cpp in Sources */, 15AE1A5719AAD40300C27E9E /* b2Settings.cpp in Sources */,
50ABBE271925AB6F00A911A9 /* CCAutoreleasePool.cpp in Sources */, 50ABBE271925AB6F00A911A9 /* CCAutoreleasePool.cpp in Sources */,
@ -11518,7 +11497,6 @@
A045F6DC1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp in Sources */, A045F6DC1BA816A1005076C7 /* CCCameraBackgroundBrush.cpp in Sources */,
B665E25A1AA80A6500DDB1C5 /* CCPUDoEnableComponentEventHandler.cpp in Sources */, B665E25A1AA80A6500DDB1C5 /* CCPUDoEnableComponentEventHandler.cpp in Sources */,
A0E749F71BA8FD7F001A8332 /* UIEditBoxImpl-common.cpp in Sources */, A0E749F71BA8FD7F001A8332 /* UIEditBoxImpl-common.cpp in Sources */,
A045F6E41BA8170A005076C7 /* CCComponentPhysics2d.cpp in Sources */,
B6DD2FB31B04825B00E47F5F /* RecastDump.cpp in Sources */, B6DD2FB31B04825B00E47F5F /* RecastDump.cpp in Sources */,
B6CAB2BB1AF9AA1A00B9B856 /* btCylinderShape.cpp in Sources */, B6CAB2BB1AF9AA1A00B9B856 /* btCylinderShape.cpp in Sources */,
15AE1BD019AAE01E00C27E9E /* CCControlHuePicker.cpp in Sources */, 15AE1BD019AAE01E00C27E9E /* CCControlHuePicker.cpp in Sources */,
@ -12140,7 +12118,6 @@
B6CAB3261AF9AA1A00B9B856 /* btGImpactBvh.cpp in Sources */, B6CAB3261AF9AA1A00B9B856 /* btGImpactBvh.cpp in Sources */,
15AE18B919AAD33D00C27E9E /* CCControlButtonLoader.cpp in Sources */, 15AE18B919AAD33D00C27E9E /* CCControlButtonLoader.cpp in Sources */,
B6CAB4041AF9AA1A00B9B856 /* btMultiBodyDynamicsWorld.cpp in Sources */, B6CAB4041AF9AA1A00B9B856 /* btMultiBodyDynamicsWorld.cpp in Sources */,
A045F6E91BA8170A005076C7 /* CCPhysicsManager.cpp in Sources */,
50ABBE761925AB6F00A911A9 /* CCEventListenerTouch.cpp in Sources */, 50ABBE761925AB6F00A911A9 /* CCEventListenerTouch.cpp in Sources */,
15AE1AD219AAD40300C27E9E /* b2RopeJoint.cpp in Sources */, 15AE1AD219AAD40300C27E9E /* b2RopeJoint.cpp in Sources */,
B29A7DCC19EE1B7700872B35 /* Skeleton.c in Sources */, B29A7DCC19EE1B7700872B35 /* Skeleton.c in Sources */,
@ -12197,7 +12174,6 @@
B6CAB2521AF9AA1A00B9B856 /* btEmptyCollisionAlgorithm.cpp in Sources */, B6CAB2521AF9AA1A00B9B856 /* btEmptyCollisionAlgorithm.cpp in Sources */,
B665E2D31AA80A6500DDB1C5 /* CCPUInterParticleColliderTranslator.cpp in Sources */, B665E2D31AA80A6500DDB1C5 /* CCPUInterParticleColliderTranslator.cpp in Sources */,
B665E3331AA80A6500DDB1C5 /* CCPUOnEmissionObserver.cpp in Sources */, B665E3331AA80A6500DDB1C5 /* CCPUOnEmissionObserver.cpp in Sources */,
A045F6E51BA8170A005076C7 /* CCComponentPhysics2d.cpp in Sources */,
1A570082180BC5A10088DEC7 /* CCActionManager.cpp in Sources */, 1A570082180BC5A10088DEC7 /* CCActionManager.cpp in Sources */,
A0534A681B872FFD006B03E5 /* CCDownloader-apple.mm in Sources */, A0534A681B872FFD006B03E5 /* CCDownloader-apple.mm in Sources */,
B665E22F1AA80A6500DDB1C5 /* CCPUBoxColliderTranslator.cpp in Sources */, B665E22F1AA80A6500DDB1C5 /* CCPUBoxColliderTranslator.cpp in Sources */,

View File

@ -24,10 +24,9 @@ THE SOFTWARE.
#include "2d/CCComponent.h" #include "2d/CCComponent.h"
NS_CC_BEGIN NS_CC_BEGIN
Component::Component(void) Component::Component()
: _owner(nullptr) : _owner(nullptr)
, _enabled(true) , _enabled(true)
{ {
@ -37,7 +36,7 @@ Component::Component(void)
#endif #endif
} }
Component::~Component(void) Component::~Component()
{ {
} }
@ -124,10 +123,11 @@ bool Component::serialize(void *ar)
return true; return true;
} }
Component* Component::create(void) Component* Component::create()
{ {
Component * ret = new (std::nothrow) Component(); Component * ret = new (std::nothrow) Component();
if (ret != nullptr && ret->init())
if (ret && ret->init())
{ {
ret->autorelease(); ret->autorelease();
} }
@ -135,37 +135,18 @@ Component* Component::create(void)
{ {
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
} }
return 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) void Component::setOwner(Node *owner)
{ {
_owner = owner; _owner = owner;
} }
bool Component::isEnabled() const void Component::setEnabled(bool enabled)
{ {
return _enabled; _enabled = enabled;
}
void Component::setEnabled(bool b)
{
_enabled = b;
} }
NS_CC_END NS_CC_END

View File

@ -26,10 +26,9 @@ THE SOFTWARE.
#define __CC_FRAMEWORK_COMPONENT_H__ #define __CC_FRAMEWORK_COMPONENT_H__
/// @cond DO_NOT_SHOW /// @cond DO_NOT_SHOW
#include <string>
#include "base/CCRef.h" #include "base/CCRef.h"
#include "base/CCScriptSupport.h" #include "base/CCScriptSupport.h"
#include <string>
NS_CC_BEGIN NS_CC_BEGIN
@ -45,37 +44,42 @@ enum {
class CC_DLL Component : public Ref class CC_DLL Component : public Ref
{ {
CC_CONSTRUCTOR_ACCESS:
/**
* @js ctor
*/
Component(void);
public: public:
static Component* create();
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual ~Component(void); virtual ~Component();
virtual bool init(); 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 onEnter();
virtual void onExit(); virtual void onExit();
virtual void onAdd(); virtual void onAdd();
virtual void onRemove(); virtual void onRemove();
virtual void update(float delta);
virtual bool serialize(void* r); CC_CONSTRUCTOR_ACCESS:
virtual bool isEnabled() const; /**
virtual void setEnabled(bool b); * @js ctor
static Component* create(void); */
Component();
const std::string& getName() const;
void setName(const std::string& name);
void setOwner(Node *pOwner);
Node* getOwner() const;
protected: protected:
Node *_owner; Node* _owner;
std::string _name; std::string _name;
bool _enabled; bool _enabled;

View File

@ -58,15 +58,16 @@ bool ComponentContainer::add(Component *com)
CCASSERT(com->getOwner() == nullptr, "Component already added. It can't be added again"); CCASSERT(com->getOwner() == nullptr, "Component already added. It can't be added again");
do do
{ {
auto typeName = typeid(*com).name(); auto componentName = com->getName();
if (_components.find(typeName) != _components.end())
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; break;
} }
_componentMap[componentName] = com;
com->retain();
com->setOwner(_owner); com->setOwner(_owner);
_components.insert(typeName, com);
_componentMap[com->getName()] = com;
com->onAdd(); com->onAdd();
ret = true; ret = true;
@ -74,14 +75,20 @@ bool ComponentContainer::add(Component *com)
return ret; return ret;
} }
bool ComponentContainer::remove(const std::string& name) bool ComponentContainer::remove(const std::string& componentName)
{ {
bool ret = false; bool ret = false;
do do
{ {
auto iter = _componentMap.find(name); auto iter = _componentMap.find(componentName);
CC_BREAK_IF(iter == _componentMap.end()); CC_BREAK_IF(iter == _componentMap.end());
remove(iter->second);
auto component = iter->second;
_componentMap.erase(componentName);
component->onRemove();
component->setOwner(nullptr);
component->release();
ret = true; ret = true;
} while(0); } while(0);
@ -91,36 +98,21 @@ bool ComponentContainer::remove(const std::string& name)
bool ComponentContainer::remove(Component *com) bool ComponentContainer::remove(Component *com)
{ {
bool ret = false; return remove(com->getName());
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;
} }
void ComponentContainer::removeAll() void ComponentContainer::removeAll()
{ {
if (!_componentMap.empty()) if (!_componentMap.empty())
{ {
for (auto iter = _components.begin(); iter != _components.end(); ++iter) for (auto iter = _componentMap.begin(); iter != _componentMap.end(); ++iter)
{ {
iter->second->onRemove(); auto component = iter->second;
iter->second->setOwner(nullptr); component->onRemove();
component->setOwner(nullptr);
component->release();
} }
_components.clear();
_componentMap.clear(); _componentMap.clear();
_owner->unscheduleUpdate(); _owner->unscheduleUpdate();
} }
@ -128,11 +120,11 @@ void ComponentContainer::removeAll()
void ComponentContainer::visit(float delta) void ComponentContainer::visit(float delta)
{ {
if (!_components.empty()) if (!_componentMap.empty())
{ {
CC_SAFE_RETAIN(_owner); CC_SAFE_RETAIN(_owner);
auto iterEnd = _components.end(); auto iterEnd = _componentMap.end();
for (auto iter = _components.begin(); iter != iterEnd; ++iter) for (auto iter = _componentMap.begin(); iter != iterEnd; ++iter)
{ {
iter->second->update(delta); iter->second->update(delta);
} }
@ -142,7 +134,7 @@ void ComponentContainer::visit(float delta)
void ComponentContainer::onEnter() void ComponentContainer::onEnter()
{ {
for (auto iter = _components.begin(); iter != _components.end(); ++iter) for (auto iter = _componentMap.begin(); iter != _componentMap.end(); ++iter)
{ {
iter->second->onEnter(); iter->second->onEnter();
} }
@ -150,7 +142,7 @@ void ComponentContainer::onEnter()
void ComponentContainer::onExit() void ComponentContainer::onExit()
{ {
for (auto iter = _components.begin(); iter != _components.end(); ++iter) for (auto iter = _componentMap.begin(); iter != _componentMap.end(); ++iter)
{ {
iter->second->onExit(); iter->second->onExit();
} }

View File

@ -48,38 +48,24 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual ~ComponentContainer(); ~ComponentContainer();
template<typename T>
T* getComponent() const
{
auto typeName = typeid(T).name();
auto iter = _components.find(typeName);
if (iter != _components.end())
{
return static_cast<T*>(iter->second);
}
return nullptr;
}
/** /**
* @js getComponent * @js getComponent
*/ */
virtual Component* get(const std::string& name) const; Component* get(const std::string& name) const;
virtual bool add(Component *com);
virtual bool remove(const std::string& name); bool add(Component *com);
virtual bool remove(Component *com); bool remove(const std::string& name);
virtual void removeAll(); bool remove(Component *com);
virtual void visit(float delta); void removeAll();
void visit(float delta);
virtual void onEnter(); void onEnter();
virtual void onExit(); void onExit();
bool isEmpty() const { return _componentMap.empty(); }
bool isEmpty() const { return _componentMap.empty(); }
private: private:
Map<std::string, Component*> _components;
std::unordered_map<std::string, Component*> _componentMap; std::unordered_map<std::string, Component*> _componentMap;
Node *_owner; Node *_owner;

View File

@ -69,7 +69,7 @@ int Node::s_globalOrderOfArrival = 1;
// MARK: Constructor, Destructor, Init // MARK: Constructor, Destructor, Init
Node::Node(void) Node::Node()
: _rotationX(0.0f) : _rotationX(0.0f)
, _rotationY(0.0f) , _rotationY(0.0f)
, _rotationZ_X(0.0f) , _rotationZ_X(0.0f)
@ -118,6 +118,9 @@ Node::Node(void)
, _cascadeColorEnabled(false) , _cascadeColorEnabled(false)
, _cascadeOpacityEnabled(false) , _cascadeOpacityEnabled(false)
, _cameraMask(1) , _cameraMask(1)
#if CC_USE_PHYSICS
, _physicsBody(nullptr)
#endif
{ {
// set default scheduler and actionManager // set default scheduler and actionManager
_director = Director::getInstance(); _director = Director::getInstance();

View File

@ -56,6 +56,7 @@ class GLProgram;
class GLProgramState; class GLProgramState;
class Material; class Material;
class Camera; class Camera;
class PhysicsBody;
/** /**
* @addtogroup _2d * @addtogroup _2d
@ -1641,22 +1642,6 @@ public:
* @return The Component by name. * @return The Component by name.
*/ */
Component* getComponent(const std::string& 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<typename T>
T* getComponent() const
{
if (_componentContainer)
return _componentContainer->getComponent<T>();
else
return nullptr;
}
/** /**
* Adds a component. * Adds a component.
@ -1862,6 +1847,19 @@ protected:
std::function<void()> _onEnterTransitionDidFinishCallback; std::function<void()> _onEnterTransitionDidFinishCallback;
std::function<void()> _onExitTransitionDidStartCallback; std::function<void()> _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: private:
CC_DISALLOW_COPY_AND_ASSIGN(Node); CC_DISALLOW_COPY_AND_ASSIGN(Node);
}; };

View File

@ -35,7 +35,7 @@ THE SOFTWARE.
#include "deprecated/CCString.h" #include "deprecated/CCString.h"
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
#include "physics/CCPhysicsManager.h" #include "physics/CCPhysicsWorld.h"
#endif #endif
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION
@ -60,7 +60,7 @@ Scene::Scene()
_navMeshDebugCamera = nullptr; _navMeshDebugCamera = nullptr;
#endif #endif
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
_physicsManager = nullptr; _physicsWorld = nullptr;
#endif #endif
_ignoreAnchorPointForPosition = true; _ignoreAnchorPointForPosition = true;
setAnchorPoint(Vec2(0.5f, 0.5f)); setAnchorPoint(Vec2(0.5f, 0.5f));
@ -90,7 +90,7 @@ Scene::~Scene()
CC_SAFE_RELEASE(_event); CC_SAFE_RELEASE(_event);
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
delete _physicsManager; delete _physicsWorld;
#endif #endif
} }
@ -279,8 +279,9 @@ Scene* Scene::createWithPhysics()
bool Scene::initWithPhysics() bool Scene::initWithPhysics()
{ {
_physicsManager = new (std::nothrow) PhysicsManager(this); #if CC_USE_PHYSICS
_physicsWorld = _physicsManager->getPhysicsWorld(); _physicsWorld = PhysicsWorld::construct(this);
#endif
bool ret = false; bool ret = false;
do do
@ -308,8 +309,8 @@ bool Scene::initWithPhysics()
void Scene::stepPhysicsAndNavigation(float deltaTime) void Scene::stepPhysicsAndNavigation(float deltaTime)
{ {
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
if (_physicsManager) if (_physicsWorld && _physicsWorld->isAutoStep())
_physicsManager->update(deltaTime); _physicsWorld->update(deltaTime);
#endif #endif
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION

View File

@ -40,7 +40,6 @@ class EventListenerCustom;
class EventCustom; class EventCustom;
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
class PhysicsWorld; class PhysicsWorld;
class PhysicsManager;
#endif #endif
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION
class Physics3DWorld; class Physics3DWorld;
@ -153,14 +152,6 @@ public:
* @js NA * @js NA
*/ */
inline PhysicsWorld* getPhysicsWorld() const { return _physicsWorld; } 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 #endif
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION
@ -190,7 +181,6 @@ protected:
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
PhysicsWorld* _physicsWorld; PhysicsWorld* _physicsWorld;
PhysicsManager* _physicsManager;
#endif #endif
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION

View File

@ -588,11 +588,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClCompile Include="..\physics3d\CCPhysics3DShape.cpp" /> <ClCompile Include="..\physics3d\CCPhysics3DShape.cpp" />
<ClCompile Include="..\physics3d\CCPhysics3DWorld.cpp" /> <ClCompile Include="..\physics3d\CCPhysics3DWorld.cpp" />
<ClCompile Include="..\physics3d\CCPhysicsSprite3D.cpp" /> <ClCompile Include="..\physics3d\CCPhysicsSprite3D.cpp" />
<ClCompile Include="..\physics\CCComponentPhysics2d.cpp" />
<ClCompile Include="..\physics\CCPhysicsBody.cpp" /> <ClCompile Include="..\physics\CCPhysicsBody.cpp" />
<ClCompile Include="..\physics\CCPhysicsContact.cpp" /> <ClCompile Include="..\physics\CCPhysicsContact.cpp" />
<ClCompile Include="..\physics\CCPhysicsJoint.cpp" /> <ClCompile Include="..\physics\CCPhysicsJoint.cpp" />
<ClCompile Include="..\physics\CCPhysicsManager.cpp" />
<ClCompile Include="..\physics\CCPhysicsShape.cpp" /> <ClCompile Include="..\physics\CCPhysicsShape.cpp" />
<ClCompile Include="..\physics\CCPhysicsWorld.cpp" /> <ClCompile Include="..\physics\CCPhysicsWorld.cpp" />
<ClCompile Include="..\platform\CCFileUtils.cpp" /> <ClCompile Include="..\platform\CCFileUtils.cpp" />
@ -693,7 +691,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClCompile Include="CCDrawNode.cpp" /> <ClCompile Include="CCDrawNode.cpp" />
<ClCompile Include="CCFastTMXLayer.cpp" /> <ClCompile Include="CCFastTMXLayer.cpp" />
<ClCompile Include="CCFastTMXTiledMap.cpp" /> <ClCompile Include="CCFastTMXTiledMap.cpp" />
<ClCompile Include="CCFont.cpp" />
<ClCompile Include="CCFontAtlas.cpp" /> <ClCompile Include="CCFontAtlas.cpp" />
<ClCompile Include="CCFontAtlasCache.cpp" /> <ClCompile Include="CCFontAtlasCache.cpp" />
<ClCompile Include="CCFontCharMap.cpp" /> <ClCompile Include="CCFontCharMap.cpp" />
@ -1200,12 +1197,10 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClInclude Include="..\physics3d\CCPhysics3DShape.h" /> <ClInclude Include="..\physics3d\CCPhysics3DShape.h" />
<ClInclude Include="..\physics3d\CCPhysics3DWorld.h" /> <ClInclude Include="..\physics3d\CCPhysics3DWorld.h" />
<ClInclude Include="..\physics3d\CCPhysicsSprite3D.h" /> <ClInclude Include="..\physics3d\CCPhysicsSprite3D.h" />
<ClInclude Include="..\physics\CCComponentPhysics2d.h" />
<ClInclude Include="..\physics\CCPhysicsBody.h" /> <ClInclude Include="..\physics\CCPhysicsBody.h" />
<ClInclude Include="..\physics\CCPhysicsContact.h" /> <ClInclude Include="..\physics\CCPhysicsContact.h" />
<ClInclude Include="..\physics\CCPhysicsHelper.h" /> <ClInclude Include="..\physics\CCPhysicsHelper.h" />
<ClInclude Include="..\physics\CCPhysicsJoint.h" /> <ClInclude Include="..\physics\CCPhysicsJoint.h" />
<ClInclude Include="..\physics\CCPhysicsManager.h" />
<ClInclude Include="..\physics\CCPhysicsShape.h" /> <ClInclude Include="..\physics\CCPhysicsShape.h" />
<ClInclude Include="..\physics\CCPhysicsWorld.h" /> <ClInclude Include="..\physics\CCPhysicsWorld.h" />
<ClInclude Include="..\platform\CCApplicationProtocol.h" /> <ClInclude Include="..\platform\CCApplicationProtocol.h" />
@ -1325,7 +1320,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClInclude Include="CCLabel.h" /> <ClInclude Include="CCLabel.h" />
<ClInclude Include="CCLabelAtlas.h" /> <ClInclude Include="CCLabelAtlas.h" />
<ClInclude Include="CCLabelBMFont.h" /> <ClInclude Include="CCLabelBMFont.h" />
<ClInclude Include="CCLabelTextFormatter.h" />
<ClInclude Include="CCLabelTTF.h" /> <ClInclude Include="CCLabelTTF.h" />
<ClInclude Include="CCLayer.h" /> <ClInclude Include="CCLayer.h" />
<ClInclude Include="CCLight.h" /> <ClInclude Include="CCLight.h" />

View File

@ -285,9 +285,6 @@
</Filter> </Filter>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="..\physics\CCComponentPhysics2d.cpp">
<Filter>physics</Filter>
</ClCompile>
<ClCompile Include="..\physics\CCPhysicsBody.cpp"> <ClCompile Include="..\physics\CCPhysicsBody.cpp">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClCompile> </ClCompile>
@ -297,9 +294,6 @@
<ClCompile Include="..\physics\CCPhysicsJoint.cpp"> <ClCompile Include="..\physics\CCPhysicsJoint.cpp">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="..\physics\CCPhysicsManager.cpp">
<Filter>physics</Filter>
</ClCompile>
<ClCompile Include="..\physics\CCPhysicsShape.cpp"> <ClCompile Include="..\physics\CCPhysicsShape.cpp">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClCompile> </ClCompile>
@ -400,9 +394,6 @@
<ClCompile Include="CCDrawNode.cpp"> <ClCompile Include="CCDrawNode.cpp">
<Filter>2d</Filter> <Filter>2d</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="CCFont.cpp">
<Filter>2d</Filter>
</ClCompile>
<ClCompile Include="CCFontAtlas.cpp"> <ClCompile Include="CCFontAtlas.cpp">
<Filter>2d</Filter> <Filter>2d</Filter>
</ClCompile> </ClCompile>
@ -1945,9 +1936,6 @@
</ClCompile> </ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\physics\CCComponentPhysics2d.h">
<Filter>physics</Filter>
</ClInclude>
<ClInclude Include="..\physics\CCPhysicsBody.h"> <ClInclude Include="..\physics\CCPhysicsBody.h">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClInclude> </ClInclude>
@ -1957,9 +1945,6 @@
<ClInclude Include="..\physics\CCPhysicsJoint.h"> <ClInclude Include="..\physics\CCPhysicsJoint.h">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\physics\CCPhysicsManager.h">
<Filter>physics</Filter>
</ClInclude>
<ClInclude Include="..\physics\CCPhysicsShape.h"> <ClInclude Include="..\physics\CCPhysicsShape.h">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClInclude> </ClInclude>
@ -2105,9 +2090,6 @@
<ClInclude Include="CCLabelBMFont.h"> <ClInclude Include="CCLabelBMFont.h">
<Filter>2d</Filter> <Filter>2d</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="CCLabelTextFormatter.h">
<Filter>2d</Filter>
</ClInclude>
<ClInclude Include="CCLabelTTF.h"> <ClInclude Include="CCLabelTTF.h">
<Filter>2d</Filter> <Filter>2d</Filter>
</ClInclude> </ClInclude>

View File

@ -469,12 +469,10 @@
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DShape.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DShape.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DWorld.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DWorld.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysicsSprite3D.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysicsSprite3D.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCComponentPhysics2d.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsBody.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsBody.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsContact.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsContact.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsHelper.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsHelper.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsJoint.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsJoint.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsManager.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsShape.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsShape.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\platform\CCApplication.h" /> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\platform\CCApplication.h" />
@ -1075,11 +1073,9 @@
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DShape.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DShape.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DWorld.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysics3DWorld.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysicsSprite3D.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics3d\CCPhysicsSprite3D.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCComponentPhysics2d.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsBody.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsBody.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsContact.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsContact.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsJoint.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsJoint.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsManager.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsShape.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsShape.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\platform\CCFileUtils.cpp" /> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\platform\CCFileUtils.cpp" />

View File

@ -213,12 +213,6 @@
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.h"> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.h">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCComponentPhysics2d.h">
<Filter>physics</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsManager.h">
<Filter>physics</Filter>
</ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\editor-support\cocostudio\CocosStudioExport.h"> <ClInclude Include="$(MSBuildThisFileDirectory)..\..\..\..\editor-support\cocostudio\CocosStudioExport.h">
<Filter>cocostudio</Filter> <Filter>cocostudio</Filter>
</ClInclude> </ClInclude>
@ -2066,12 +2060,6 @@
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.cpp"> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsWorld.cpp">
<Filter>physics</Filter> <Filter>physics</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCComponentPhysics2d.cpp">
<Filter>physics</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\physics\CCPhysicsManager.cpp">
<Filter>physics</Filter>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\editor-support\cocostudio\CCActionFrame.cpp"> <ClCompile Include="$(MSBuildThisFileDirectory)..\..\..\..\editor-support\cocostudio\CCActionFrame.cpp">
<Filter>cocostudio\action</Filter> <Filter>cocostudio\action</Filter>
</ClCompile> </ClCompile>

View File

@ -200,8 +200,6 @@ physics/CCPhysicsContact.cpp \
physics/CCPhysicsJoint.cpp \ physics/CCPhysicsJoint.cpp \
physics/CCPhysicsShape.cpp \ physics/CCPhysicsShape.cpp \
physics/CCPhysicsWorld.cpp \ physics/CCPhysicsWorld.cpp \
physics/CCComponentPhysics2d.cpp \
physics/CCPhysicsManager.cpp \
physics3d/CCPhysics3D.cpp \ physics3d/CCPhysics3D.cpp \
physics3d/CCPhysics3DWorld.cpp \ physics3d/CCPhysics3DWorld.cpp \
physics3d/CCPhysics3DComponent.cpp \ physics3d/CCPhysics3DComponent.cpp \

View File

@ -186,8 +186,6 @@ THE SOFTWARE.
#include "physics/CCPhysicsJoint.h" #include "physics/CCPhysicsJoint.h"
#include "physics/CCPhysicsShape.h" #include "physics/CCPhysicsShape.h"
#include "physics/CCPhysicsWorld.h" #include "physics/CCPhysicsWorld.h"
#include "physics/CCComponentPhysics2d.h"
#include "physics/CCPhysicsManager.h"
// platform // platform
#include "platform/CCCommon.h" #include "platform/CCCommon.h"

View File

@ -30,12 +30,15 @@ using namespace cocos2d;
namespace cocostudio { namespace cocostudio {
IMPLEMENT_CLASS_COMPONENT_INFO(ComAttribute) 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(); _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()); return DICTOOL->getStringValue_json(_doc, key.c_str());
} }
ComAttribute* ComAttribute::create(void) ComAttribute* ComAttribute::create()
{ {
ComAttribute * pRet = new (std::nothrow) ComAttribute(); ComAttribute * pRet = new (std::nothrow) ComAttribute();
if (pRet && pRet->init()) if (pRet && pRet->init())

View File

@ -47,6 +47,8 @@ public:
virtual ~ComAttribute(void); virtual ~ComAttribute(void);
public: public:
const static std::string COMPONENT_NAME;
static ComAttribute* create(void); static ComAttribute* create(void);
virtual bool init() override; virtual bool init() override;
virtual bool serialize(void* r) override; virtual bool serialize(void* r) override;

View File

@ -29,14 +29,17 @@ THE SOFTWARE.
namespace cocostudio { namespace cocostudio {
IMPLEMENT_CLASS_COMPONENT_INFO(ComAudio) IMPLEMENT_CLASS_COMPONENT_INFO(ComAudio)
ComAudio::ComAudio(void)
const std::string ComAudio::COMPONENT_NAME = "CCComAudio";
ComAudio::ComAudio()
: _filePath("") : _filePath("")
, _loop(false) , _loop(false)
{ {
_name = "CCComAudio"; _name = COMPONENT_NAME;
} }
ComAudio::~ComAudio(void) ComAudio::~ComAudio()
{ {
} }
@ -66,17 +69,6 @@ void ComAudio::onRemove()
stopAllEffects(); stopAllEffects();
} }
bool ComAudio::isEnabled() const
{
return _enabled;
}
void ComAudio::setEnabled(bool b)
{
_enabled = b;
}
bool ComAudio::serialize(void* r) bool ComAudio::serialize(void* r)
{ {
bool ret = false; bool ret = false;
@ -142,7 +134,7 @@ bool ComAudio::serialize(void* r)
setLoop(loop); setLoop(loop);
playBackgroundMusic(filePath.c_str(), 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()); preloadEffect(filePath.c_str());
} }
@ -155,7 +147,7 @@ bool ComAudio::serialize(void* r)
return ret; return ret;
} }
ComAudio* ComAudio::create(void) ComAudio* ComAudio::create()
{ {
ComAudio * pRet = new (std::nothrow) ComAudio(); ComAudio * pRet = new (std::nothrow) ComAudio();
if (pRet && pRet->init()) if (pRet && pRet->init())

View File

@ -33,21 +33,23 @@ namespace cocostudio {
class CC_STUDIO_DLL ComAudio : public cocos2d::Component class CC_STUDIO_DLL ComAudio : public cocos2d::Component
{ {
DECLARE_CLASS_COMPONENT_INFO DECLARE_CLASS_COMPONENT_INFO
public: public:
const static std::string COMPONENT_NAME;
/** /**
* @js ctor * @js ctor
*/ */
ComAudio(void); ComAudio();
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual ~ComAudio(void); virtual ~ComAudio();
public: public:
static ComAudio* create();
virtual bool init() override; virtual bool init() override;
/** /**
* @js NA * @js NA
@ -69,12 +71,8 @@ public:
* @lua NA * @lua NA
*/ */
virtual void onRemove() override; 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: public:
void end(); void end();
void preloadBackgroundMusic(const char* pszFilePath); void preloadBackgroundMusic(const char* pszFilePath);

View File

@ -28,12 +28,15 @@ THE SOFTWARE.
namespace cocostudio { namespace cocostudio {
IMPLEMENT_CLASS_COMPONENT_INFO(ComController) 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 ComController* ComController::create()
{
return _enabled;
}
void ComController::setEnabled(bool b)
{
_enabled = b;
}
ComController* ComController::create(void)
{ {
ComController * pRet = new (std::nothrow) ComController(); ComController * pRet = new (std::nothrow) ComController();
if (pRet && pRet->init()) if (pRet && pRet->init())

View File

@ -34,46 +34,50 @@ namespace cocostudio {
class CC_STUDIO_DLL ComController : public cocos2d::Component, public InputDelegate class CC_STUDIO_DLL ComController : public cocos2d::Component, public InputDelegate
{ {
DECLARE_CLASS_COMPONENT_INFO DECLARE_CLASS_COMPONENT_INFO
public: public:
/** /**
* @js ctor * @js ctor
*/ */
ComController(void); ComController();
public: public:
const static std::string COMPONENT_NAME;
static ComController* create();
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual ~ComController(void); virtual ~ComController();
virtual bool init() override; virtual bool init() override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void onEnter() override; virtual void onEnter() override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void onExit() override; virtual void onExit() override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void onAdd() override; virtual void onAdd() override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void onRemove() override; virtual void onRemove() override;
virtual void update(float delta) override; virtual void update(float delta) override;
virtual bool isEnabled() const override;
virtual void setEnabled(bool b) override;
static ComController* create(void);
}; };
} }

View File

@ -23,18 +23,19 @@
****************************************************************************/ ****************************************************************************/
#include "CCComExtensionData.h" #include "CCComExtensionData.h"
#include "cocostudio/ActionTimeline/CCActionTimeline.h" #include "cocostudio/ActionTimeline/CCActionTimeline.h"
namespace cocostudio namespace cocostudio
{ {
IMPLEMENT_CLASS_COMPONENT_INFO(ComExtensionData) IMPLEMENT_CLASS_COMPONENT_INFO(ComExtensionData)
const std::string ComExtensionData::COMPONENT_NAME = "ComExtensionData";
ComExtensionData::ComExtensionData() ComExtensionData::ComExtensionData()
: _customProperty("") : _customProperty("")
, _timelineData(nullptr) , _timelineData(nullptr)
{ {
_name = "ComExtensionData"; _name = COMPONENT_NAME;
} }
ComExtensionData::~ComExtensionData() ComExtensionData::~ComExtensionData()

View File

@ -44,6 +44,8 @@ namespace cocostudio
{ {
DECLARE_CLASS_COMPONENT_INFO DECLARE_CLASS_COMPONENT_INFO
public: public:
const static std::string COMPONENT_NAME;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA

View File

@ -30,13 +30,15 @@ using namespace cocos2d;
namespace cocostudio { namespace cocostudio {
IMPLEMENT_CLASS_COMPONENT_INFO(ComRender) IMPLEMENT_CLASS_COMPONENT_INFO(ComRender)
ComRender::ComRender(void)
const std::string ComRender::COMPONENT_NAME = "CCComRender";
ComRender::ComRender()
: _render(nullptr) : _render(nullptr)
{ {
_name = "CCComRender"; _name = COMPONENT_NAME;
} }
ComRender::ComRender(cocos2d::Node *node, const char *comName) ComRender::ComRender(cocos2d::Node *node, const char *comName)
{ {
if (node != nullptr) if (node != nullptr)
@ -47,7 +49,7 @@ ComRender::ComRender(cocos2d::Node *node, const char *comName)
_name.assign(comName); _name.assign(comName);
} }
ComRender::~ComRender(void) ComRender::~ComRender()
{ {
CC_SAFE_RELEASE_NULL(_render); CC_SAFE_RELEASE_NULL(_render);
} }
@ -347,7 +349,7 @@ bool ComRender::serialize(void* r)
return ret; return ret;
} }
ComRender* ComRender::create(void) ComRender* ComRender::create()
{ {
ComRender * ret = new (std::nothrow) ComRender(); ComRender * ret = new (std::nothrow) ComRender();
if (ret != nullptr && ret->init()) if (ret != nullptr && ret->init())

View File

@ -34,19 +34,13 @@ namespace cocostudio {
class CC_STUDIO_DLL ComRender : public cocos2d::Component class CC_STUDIO_DLL ComRender : public cocos2d::Component
{ {
DECLARE_CLASS_COMPONENT_INFO 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: public:
const static std::string COMPONENT_NAME;
static ComRender* create();
static ComRender* create(cocos2d::Node *node, const char *comName);
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
@ -71,12 +65,21 @@ public:
virtual cocos2d::Node* getNode(); virtual cocos2d::Node* getNode();
virtual void setNode(cocos2d::Node *node); virtual void setNode(cocos2d::Node *node);
static ComRender* create(void); CC_CONSTRUCTOR_ACCESS:
static ComRender* create(cocos2d::Node *node, const char *comName); /**
* @js ctor
*/
ComRender();
ComRender(cocos2d::Node *node, const char *comName);
/**
* @js NA
* @lua NA
*/
virtual ~ComRender();
private: private:
bool readJson(const std::string &fileName, rapidjson::Document &doc); bool readJson(const std::string &fileName, rapidjson::Document &doc);
private:
cocos2d::Node *_render; cocos2d::Node *_render;
}; };

View File

@ -223,15 +223,15 @@ std::string SceneReader::getComponentClassName(const std::string &name)
{ {
comName = "ComRender"; comName = "ComRender";
} }
else if (name == "CCComAudio" || name == "CCBackgroundAudio") else if (name == ComAudio::COMPONENT_NAME || name == "CCBackgroundAudio")
{ {
comName = "ComAudio"; comName = "ComAudio";
} }
else if (name == "CCComController") else if (name == ComController::COMPONENT_NAME)
{ {
comName = "ComController"; comName = "ComController";
} }
else if (name == "CCComAttribute") else if (name == ComAttribute::COMPONENT_NAME)
{ {
comName = "ComAttribute"; comName = "ComAttribute";
} }

View File

@ -414,10 +414,10 @@ namespace cocostudio
std::string customProperty = options->customProperty()->c_str(); std::string customProperty = options->customProperty()->c_str();
ComExtensionData* extensionData = ComExtensionData::create(); ComExtensionData* extensionData = ComExtensionData::create();
extensionData->setCustomProperty(customProperty);\ extensionData->setCustomProperty(customProperty);
if (node->getComponent("ComExtensionData")) if (node->getComponent(ComExtensionData::COMPONENT_NAME))
{ {
node->removeComponent("ComExtensionData"); node->removeComponent(ComExtensionData::COMPONENT_NAME);
} }
node->addComponent(extensionData); node->addComponent(extensionData);
} }

View File

@ -512,9 +512,9 @@ namespace cocostudio
ComExtensionData* extensionData = ComExtensionData::create(); ComExtensionData* extensionData = ComExtensionData::create();
extensionData->setCustomProperty(customProperty); extensionData->setCustomProperty(customProperty);
extensionData->setActionTag(actionTag); extensionData->setActionTag(actionTag);
if (node->getComponent("ComExtensionData")) if (node->getComponent(ComExtensionData::COMPONENT_NAME))
{ {
node->removeComponent("ComExtensionData"); node->removeComponent(ComExtensionData::COMPONENT_NAME);
} }
node->addComponent(extensionData); node->addComponent(extensionData);

View File

@ -808,9 +808,9 @@ namespace cocostudio
ComExtensionData* extensionData = ComExtensionData::create(); ComExtensionData* extensionData = ComExtensionData::create();
extensionData->setCustomProperty(customProperty); extensionData->setCustomProperty(customProperty);
extensionData->setActionTag(actionTag); extensionData->setActionTag(actionTag);
if (node->getComponent("ComExtensionData")) if (node->getComponent(ComExtensionData::COMPONENT_NAME))
{ {
node->removeComponent(extensionData); node->removeComponent(ComExtensionData::COMPONENT_NAME);
} }
node->addComponent(extensionData); node->addComponent(extensionData);

View File

@ -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<ComponentPhysics2d>();
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

View File

@ -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

View File

@ -35,7 +35,6 @@
#include "physics/CCPhysicsJoint.h" #include "physics/CCPhysicsJoint.h"
#include "physics/CCPhysicsWorld.h" #include "physics/CCPhysicsWorld.h"
#include "physics/CCPhysicsHelper.h" #include "physics/CCPhysicsHelper.h"
#include "physics/CCComponentPhysics2d.h"
static inline void cpBodyUpdateVelocityWithoutGravity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt) 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 NS_CC_BEGIN
extern const float PHYSICS_INFINITY; extern const float PHYSICS_INFINITY;
const std::string PhysicsBody::COMPONENT_NAME = "PhysicsBody";
namespace namespace
{ {
static const float MASS_DEFAULT = 1.0; static const float MASS_DEFAULT = 1.0;
@ -55,7 +56,6 @@ PhysicsBody::PhysicsBody()
: _world(nullptr) : _world(nullptr)
, _cpBody(nullptr) , _cpBody(nullptr)
, _dynamic(true) , _dynamic(true)
, _enabled(true)
, _rotationEnabled(true) , _rotationEnabled(true)
, _gravityEnabled(true) , _gravityEnabled(true)
, _massDefault(true) , _massDefault(true)
@ -71,9 +71,10 @@ PhysicsBody::PhysicsBody()
, _rotationOffset(0) , _rotationOffset(0)
, _recordedRotation(0.0f) , _recordedRotation(0.0f)
, _recordedAngle(0.0) , _recordedAngle(0.0)
, _componentBelongsTo(nullptr)
, _massSetByUser(false) , _massSetByUser(false)
, _momentSetByUser(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); CC_SAFE_DELETE(body);
return nullptr; return nullptr;
} }
@ -255,7 +256,7 @@ bool PhysicsBody::init()
{ {
do do
{ {
_cpBody = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); _cpBody = cpBodyNew(_mass, _moment);
CC_BREAK_IF(_cpBody == nullptr); 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) void PhysicsBody::setRotation(float rotation)
{ {
_recordedRotation = 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 Vec2 PhysicsBody::getPosition() const
{ {
return Vec2(_cpBody->p.x - _positionOffset.x, _cpBody->p.y - _positionOffset.y); 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() float PhysicsBody::getRotation()
{ {
if (_recordedAngle != cpBodyGetAngle(_cpBody)) { if (_recordedAngle != cpBodyGetAngle(_cpBody)) {
@ -409,12 +425,7 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/*
return shape; return shape;
} }
void PhysicsBody::applyForce(const Vect& force) void PhysicsBody::applyForce(const Vec2& force, const Vec2& offset)
{
applyForce(force, Vec2::ZERO);
}
void PhysicsBody::applyForce(const Vect& force, const Vec2& offset)
{ {
if (_dynamic && _mass != PHYSICS_INFINITY) if (_dynamic && _mass != PHYSICS_INFINITY)
{ {
@ -427,19 +438,14 @@ void PhysicsBody::resetForces()
cpBodyResetForces(_cpBody); cpBodyResetForces(_cpBody);
} }
void PhysicsBody::applyImpulse(const Vect& impulse) void PhysicsBody::applyImpulse(const Vec2& impulse, const Vec2& offset)
{
applyImpulse(impulse, Vec2());
}
void PhysicsBody::applyImpulse(const Vect& impulse, const Vec2& offset)
{ {
cpBodyApplyImpulse(_cpBody, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); cpBodyApplyImpulse(_cpBody, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset));
} }
void PhysicsBody::applyTorque(float torque) void PhysicsBody::applyTorque(float torque)
{ {
cpBodySetTorque(_cpBody, PhysicsHelper::float2cpfloat(torque)); cpBodySetTorque(_cpBody, torque);
} }
void PhysicsBody::setMass(float mass) void PhysicsBody::setMass(float mass)
@ -559,7 +565,7 @@ void PhysicsBody::addMoment(float moment)
// the static body's mass and moment is always infinity // the static body's mass and moment is always infinity
if (_rotationEnabled && _dynamic) if (_rotationEnabled && _dynamic)
{ {
cpBodySetMoment(_cpBody, PhysicsHelper::float2cpfloat(_moment)); cpBodySetMoment(_cpBody, _moment);
} }
} }
@ -597,7 +603,7 @@ void PhysicsBody::setAngularVelocity(float velocity)
return; return;
} }
cpBodySetAngVel(_cpBody, PhysicsHelper::float2cpfloat(velocity)); cpBodySetAngVel(_cpBody, velocity);
} }
float PhysicsBody::getAngularVelocity() float PhysicsBody::getAngularVelocity()
@ -607,7 +613,7 @@ float PhysicsBody::getAngularVelocity()
void PhysicsBody::setVelocityLimit(float limit) void PhysicsBody::setVelocityLimit(float limit)
{ {
cpBodySetVelLimit(_cpBody, PhysicsHelper::float2cpfloat(limit)); cpBodySetVelLimit(_cpBody, limit);
} }
float PhysicsBody::getVelocityLimit() float PhysicsBody::getVelocityLimit()
@ -617,7 +623,7 @@ float PhysicsBody::getVelocityLimit()
void PhysicsBody::setAngularVelocityLimit(float limit) void PhysicsBody::setAngularVelocityLimit(float limit)
{ {
cpBodySetAngVelLimit(_cpBody, PhysicsHelper::float2cpfloat(limit)); cpBodySetAngVelLimit(_cpBody, limit);
} }
float PhysicsBody::getAngularVelocityLimit() float PhysicsBody::getAngularVelocityLimit()
@ -634,7 +640,7 @@ void PhysicsBody::setMoment(float moment)
// the static body's mass and moment is always infinity // the static body's mass and moment is always infinity
if (_rotationEnabled && _dynamic) if (_rotationEnabled && _dynamic)
{ {
cpBodySetMoment(_cpBody, PhysicsHelper::float2cpfloat(_moment)); cpBodySetMoment(_cpBody, _moment);
} }
} }
@ -719,21 +725,10 @@ void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/)
void PhysicsBody::removeFromWorld() void PhysicsBody::removeFromWorld()
{ {
if (_world) removeFromPhysicsWorld();
{
_world->removeBody(this);
}
} }
Node* PhysicsBody::getNode() const void PhysicsBody::setEnabled(bool enable)
{
if (_componentBelongsTo)
return _componentBelongsTo->getOwner();
else
return nullptr;
}
void PhysicsBody::setEnable(bool enable)
{ {
if (_enabled != enable) if (_enabled != enable)
{ {
@ -762,7 +757,8 @@ void PhysicsBody::setResting(bool rest) const
if (rest && !isResting()) if (rest && !isResting())
{ {
cpBodySleep(_cpBody); cpBodySleep(_cpBody);
}else if(!rest && isResting()) }
else if(!rest && isResting())
{ {
cpBodyActivate(_cpBody); 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) void PhysicsBody::setRotationOffset(float rotation)
{ {
if (std::abs(_rotationOffset - rotation) > 0.5f) 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))); 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 NS_CC_END
#endif // CC_USE_PHYSICS #endif // CC_USE_PHYSICS

View File

@ -28,7 +28,7 @@
#include "base/ccConfig.h" #include "base/ccConfig.h"
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
#include "base/CCRef.h" #include "2d/CCComponent.h"
#include "math/CCGeometry.h" #include "math/CCGeometry.h"
#include "physics/CCPhysicsShape.h" #include "physics/CCPhysicsShape.h"
#include "base/CCVector.h" #include "base/CCVector.h"
@ -38,14 +38,11 @@ struct cpBody;
NS_CC_BEGIN NS_CC_BEGIN
class Node; class Node;
class Sprite;
class PhysicsWorld; class PhysicsWorld;
class PhysicsJoint; class PhysicsJoint;
class ComponentPhysics2d;
typedef Vec2 Vect; typedef Vec2 Vect;
const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); 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. * 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(). * 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: public:
const static std::string COMPONENT_NAME;
/** /**
Create a body with default mass and moment. * Create a body with default mass and moment.
*
This default mass value is 1.0. * This default mass value is 1.0.
This default moment value is 200. * This default moment value is 200.
@return An autoreleased PhysicsBody object pointer. * @return An autoreleased PhysicsBody object pointer.
*/ */
static PhysicsBody* create(); static PhysicsBody* create();
/** /**
Create a body with mass and default moment. * Create a body with mass and default moment.
*
@param mass This body's mass. * @param mass This body's mass.
@return An autoreleased PhysicsBody object pointer. * @return An autoreleased PhysicsBody object pointer.
*/ */
static PhysicsBody* create(float mass); static PhysicsBody* create(float mass);
/** /**
Create a body with mass and moment. * Create a body with mass and moment.
*
@param mass This body's mass. * @param mass This body's mass.
@param moment This body's moment. * @param moment This body's moment.
@return An autoreleased PhysicsBody object pointer. * @return An autoreleased PhysicsBody object pointer.
*/ */
static PhysicsBody* create(float mass, float moment); static PhysicsBody* create(float mass, float moment);
/** /**
Create a body contains a circle. * Create a body contains a circle.
*
@param radius A float number, it is the circle's radius. * @param radius A float number, it is the circle's radius.
@param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
@param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates. * @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
@return An autoreleased PhysicsBody object pointer. * @return An autoreleased PhysicsBody object pointer.
*/ */
static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO); static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
/** /**
* Create a body contains a box shape. * Create a body contains a box shape.
* *
* @param size Size contains this box's width and height. * @param size Size contains this box's width and height.
@ -110,7 +109,7 @@ public:
* @return An autoreleased PhysicsBody object pointer. * @return An autoreleased PhysicsBody object pointer.
*/ */
static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO); 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. * @brief Create a body contains a polygon shape.
* *
@ -121,10 +120,10 @@ public:
* @return An autoreleased PhysicsBody object pointer. * @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); 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 a It's the edge's begin position.
* @param b It's the edge's end position. * @param b It's the edge's end position.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
@ -132,10 +131,9 @@ public:
* @return An autoreleased PhysicsBody object pointer. * @return An autoreleased PhysicsBody object pointer.
*/ */
static PhysicsBody* createEdgeSegment(const Vec2& a, const Vec2& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); 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 size Size contains this box's width and height.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width. * @param border It's a edge's border width.
@ -143,10 +141,10 @@ public:
* @return An autoreleased PhysicsBody object pointer. * @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); 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 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 count An interger number, contains the count of the points array.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
@ -154,18 +152,18 @@ public:
* @return An autoreleased PhysicsBody object pointer. * @return An autoreleased PhysicsBody object pointer.
*/ */
static PhysicsBody* createEdgePolygon(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); 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 points A Vec2 object pointer, it contains an array of points.
* @param count An interger number, contains the count of the points array. * @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 material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width. * @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); static PhysicsBody* createEdgeChain(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
/** /**
* @brief Add a shape to body. * @brief Add a shape to body.
* @param shape The shape to be added. * @param shape The shape to be added.
@ -189,90 +187,69 @@ public:
void removeShape(int tag, bool reduceMassAndMoment = true); 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. * @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); void removeAllShapes(bool reduceMassAndMoment = true);
/** /**
Get the body shapes. * Get the body shapes.
*
* @return A Vector<PhysicsShape*> object contains PhysicsShape pointer. * @return A Vector<PhysicsShape*> object contains PhysicsShape pointer.
*/ */
inline const Vector<PhysicsShape*>& getShapes() const { return _shapes; } inline const Vector<PhysicsShape*>& 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. * get the shape of the body.
*
@param tag An interger number that identifies a PhysicsShape object. * @param tag An interger number that identifies a PhysicsShape object.
@return A PhysicsShape object pointer or nullptr if no shapes were found. * @return A PhysicsShape object pointer or nullptr if no shapes were found.
*/ */
PhysicsShape* getShape(int tag) const; PhysicsShape* getShape(int tag) const;
/** /**
Applies a continuous force to body. * Applies a continuous force to body.
*
@param force The force is applies to this body. * @param force The force is applies to this body.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in world coordinates.
*/ */
virtual void applyForce(const Vect& force); virtual void applyForce(const Vec2& force, const Vec2& offset = Vec2::ZERO);
/**
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 bodys center of gravity in world coordinates.
*/
virtual void applyForce(const Vect& force, const Vec2& offset);
/** /**
reset all the force applied to body. * reset all the force applied to body.
*/ */
virtual void resetForces(); virtual void resetForces();
/** /**
Applies a immediate force to body. * Applies a immediate force to body.
*
@param impulse The impulse is applies to this body. * @param impulse The impulse is applies to this body.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in world coordinates.
*/ */
virtual void applyImpulse(const Vect& impulse); virtual void applyImpulse(const Vec2& impulse, const Vec2& offset = Vec2::ZERO);
/**
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 bodys center of gravity in world coordinates.
*/
virtual void applyImpulse(const Vect& impulse, const Vec2& offset);
/** /**
Applies a torque force to body. * Applies a torque force to body.
*
@param torque The torque is applies to this body. * @param torque The torque is applies to this body.
*/ */
virtual void applyTorque(float torque); virtual void applyTorque(float torque);
/** /**
Set the velocity of a body. * Set the velocity of a body.
*
@param velocity The velocity is set to this 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. */ /** Get the velocity of a body. */
virtual Vec2 getVelocity(); virtual Vec2 getVelocity();
/** /**
Set the angular velocity of a body. * Set the angular velocity of a body.
*
@param velocity The angular velocity is set to this body. * @param velocity The angular velocity is set to this body.
*/ */
virtual void setAngularVelocity(float velocity); virtual void setAngularVelocity(float velocity);
@ -302,11 +279,12 @@ public:
/** get the world body added to. */ /** get the world body added to. */
inline PhysicsWorld* getWorld() const { return _world; } inline PhysicsWorld* getWorld() const { return _world; }
/** get all joints the body have */ /** get all joints the body have */
inline const std::vector<PhysicsJoint*>& getJoints() const { return _joints; } inline const std::vector<PhysicsJoint*>& getJoints() const { return _joints; }
/** get the sprite the body set to. */ /** get the node the body set to. */
Node* getNode() const; Node* getNode() const { return _owner; }
/** /**
* A mask that defines which categories this physics body belongs to. * A mask that defines which categories this physics body belongs to.
@ -333,23 +311,23 @@ public:
void setCollisionBitmask(int bitmask); 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) * @return If there is no shape in body, return default value.(0xFFFFFFFF)
*/ */
int getCategoryBitmask() const; 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) * @return If there is no shape in body, return default value.(0x00000000)
*/ */
int getContactTestBitmask() const; int getContactTestBitmask() const;
/** /**
Return bitmask of first shape. * Return bitmask of first shape.
*
@return If there is no shape in body, return default value.(0xFFFFFFFF) * @return If there is no shape in body, return default value.(0xFFFFFFFF)
*/ */
int getCollisionBitmask() const; int getCollisionBitmask() const;
@ -362,21 +340,21 @@ public:
void setGroup(int group); void setGroup(int group);
/** /**
Return group of first shape. * Return group of first shape.
*
@return If there is no shape in body, return default value.(0) * @return If there is no shape in body, return default value.(0)
*/ */
int getGroup() const; int getGroup() const;
/** get the body position. */ /** get the body position. */
Vec2 getPosition() const; Vec2 getPosition() const;
/** get the body rotation. */ /** get the body rotation. */
float getRotation(); float getRotation();
/** set body position offset, it's the position witch relative to node */ /** set body position offset, it's the position witch relative to node */
void setPositionOffset(const Vec2& position); void setPositionOffset(const Vec2& position);
/** get body position offset. */ /** get body position offset. */
const Vec2& getPositionOffset() const { return _positionOffset; } const Vec2& getPositionOffset() const { return _positionOffset; }
@ -408,6 +386,7 @@ public:
/** Get the body mass. */ /** Get the body mass. */
inline float getMass() const { return _mass; } inline float getMass() const { return _mass; }
/** /**
* @brief Add mass to body. * @brief Add mass to body.
* *
@ -453,6 +432,7 @@ public:
/** Get angular damping. */ /** Get angular damping. */
inline float getAngularDamping() const { return _angularDamping; } inline float getAngularDamping() const { return _angularDamping; }
/** /**
* Set angular damping. * Set angular damping.
* *
@ -466,20 +446,13 @@ public:
/** set body to rest */ /** set body to rest */
void setResting(bool rest) const; 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. * Set the enable value.
* *
* If the body it isn't enabled, it will not has simulation by world. * 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. */ /** Whether the body can rotation. */
inline bool isRotationEnabled() const { return _rotationEnabled; } inline bool isRotationEnabled() const { return _rotationEnabled; }
@ -507,33 +480,42 @@ public:
/** Get the rigid body of chipmunk. */ /** Get the rigid body of chipmunk. */
cpBody* getCPBody() const { return _cpBody; } cpBody* getCPBody() const { return _cpBody; }
virtual void onEnter() override;
virtual void onExit() override;
virtual void onAdd() override;
virtual void onRemove() override;
protected: protected:
PhysicsBody();
virtual ~PhysicsBody();
virtual bool init();
bool init(); virtual void setPosition(float positionX, float positionY);
virtual void setPosition(const Vec2& position);
virtual void setRotation(float rotation); virtual void setRotation(float rotation);
virtual void setScale(float scaleX, float scaleY); virtual void setScale(float scaleX, float scaleY);
void update(float delta); void update(float delta);
void removeJoint(PhysicsJoint* joint); void removeJoint(PhysicsJoint* joint);
inline void updateDamping() { _isDamping = _linearDamping != 0.0f || _angularDamping != 0.0f; } inline void updateDamping() { _isDamping = _linearDamping != 0.0f || _angularDamping != 0.0f; }
protected: void addToPhysicsWorld();
PhysicsBody(); void removeFromPhysicsWorld();
virtual ~PhysicsBody();
void beforeSimulation(const Mat4& parentToWorldTransform, const Mat4& nodeToWorldTransform, float scaleX, float scaleY, float rotation);
void afterSimulation(const Mat4& parentToWorldTransform, float parentRotation);
protected: protected:
std::vector<PhysicsJoint*> _joints; std::vector<PhysicsJoint*> _joints;
Vector<PhysicsShape*> _shapes; Vector<PhysicsShape*> _shapes;
PhysicsWorld* _world; PhysicsWorld* _world;
// weak reference
ComponentPhysics2d *_componentBelongsTo;
cpBody* _cpBody; cpBody* _cpBody;
bool _dynamic; bool _dynamic;
bool _enabled;
bool _rotationEnabled; bool _rotationEnabled;
bool _gravityEnabled; bool _gravityEnabled;
bool _massDefault; bool _massDefault;
@ -545,6 +527,7 @@ protected:
bool _isDamping; bool _isDamping;
float _linearDamping; float _linearDamping;
float _angularDamping; float _angularDamping;
int _tag; int _tag;
// when setMass() is invoked, it means body's mass is not calculated by shapes // when setMass() is invoked, it means body's mass is not calculated by shapes
@ -557,13 +540,19 @@ protected:
float _recordedRotation; float _recordedRotation;
double _recordedAngle; 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 PhysicsWorld;
friend class PhysicsShape; friend class PhysicsShape;
friend class PhysicsJoint; friend class PhysicsJoint;
friend class Node;
friend class Layer;
friend class ProtectedNode;
friend class ComponentPhysics2d;
}; };
/** @} */ /** @} */

View File

@ -137,7 +137,7 @@ void PhysicsContactPreSolve::setFriction(float friction)
static_cast<cpArbiter*>(_contactInfo)->u = friction; static_cast<cpArbiter*>(_contactInfo)->u = friction;
} }
void PhysicsContactPreSolve::setSurfaceVelocity(const Vect& velocity) void PhysicsContactPreSolve::setSurfaceVelocity(const Vec2& velocity)
{ {
static_cast<cpArbiter*>(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(velocity); static_cast<cpArbiter*>(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(velocity);
} }

View File

@ -40,8 +40,6 @@ class PhysicsShape;
class PhysicsBody; class PhysicsBody;
class PhysicsWorld; class PhysicsWorld;
typedef Vec2 Vect;
typedef struct CC_DLL PhysicsContactData typedef struct CC_DLL PhysicsContactData
{ {
static const int POINT_MAX = 4; static const int POINT_MAX = 4;
@ -162,7 +160,7 @@ public:
/** Set the friction.*/ /** Set the friction.*/
void setFriction(float friction); void setFriction(float friction);
/** Set the surface velocity.*/ /** Set the surface velocity.*/
void setSurfaceVelocity(const Vect& velocity); void setSurfaceVelocity(const Vec2& velocity);
/** Ignore the rest of the contact presolve and postsolve callbacks. */ /** Ignore the rest of the contact presolve and postsolve callbacks. */
void ignore(); void ignore();

View File

@ -64,9 +64,6 @@ public:
/** Make cpFloat type convert to float type. */ /** Make cpFloat type convert to float type. */
static float cpfloat2float(cpFloat f) { return f; } 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. */ /** 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); } 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); }

View File

@ -139,7 +139,7 @@ void PhysicsJoint::setMaxForce(float force)
_maxForce = force; _maxForce = force;
for (auto joint : _cpConstraints) 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(), auto joint = cpSlideJointNew(_bodyA->getCPBody(), _bodyB->getCPBody(),
PhysicsHelper::point2cpv(_anchr1), PhysicsHelper::point2cpv(_anchr1),
PhysicsHelper::point2cpv(_anchr2), PhysicsHelper::point2cpv(_anchr2),
PhysicsHelper::float2cpfloat(_min), _min,
PhysicsHelper::float2cpfloat(_max)); _max);
CC_BREAK_IF(joint == nullptr); CC_BREAK_IF(joint == nullptr);
_cpConstraints.push_back(joint); _cpConstraints.push_back(joint);
@ -289,7 +289,7 @@ float PhysicsJointLimit::getMin() const
void PhysicsJointLimit::setMin(float min) void PhysicsJointLimit::setMin(float min)
{ {
cpSlideJointSetMin(_cpConstraints.front(), PhysicsHelper::float2cpfloat(min)); cpSlideJointSetMin(_cpConstraints.front(), min);
} }
float PhysicsJointLimit::getMax() const float PhysicsJointLimit::getMax() const
@ -299,7 +299,7 @@ float PhysicsJointLimit::getMax() const
void PhysicsJointLimit::setMax(float max) void PhysicsJointLimit::setMax(float max)
{ {
cpSlideJointSetMax(_cpConstraints.front(), PhysicsHelper::float2cpfloat(max)); cpSlideJointSetMax(_cpConstraints.front(), max);
} }
Vec2 PhysicsJointLimit::getAnchr1() const Vec2 PhysicsJointLimit::getAnchr1() const
@ -362,7 +362,7 @@ float PhysicsJointDistance::getDistance() const
void PhysicsJointDistance::setDistance(float distance) 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) 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(), _bodyB->getCPBody(),
PhysicsHelper::point2cpv(_anchr1), PhysicsHelper::point2cpv(_anchr1),
PhysicsHelper::point2cpv(_anchr2), PhysicsHelper::point2cpv(_anchr2),
PhysicsHelper::float2cpfloat(_bodyB->local2World(_anchr1).getDistance(_bodyA->local2World(_anchr2))), _bodyB->local2World(_anchr1).getDistance(_bodyA->local2World(_anchr2)),
PhysicsHelper::float2cpfloat(_stiffness), _stiffness,
PhysicsHelper::float2cpfloat(_damping)); _damping);
CC_BREAK_IF(joint == nullptr); CC_BREAK_IF(joint == nullptr);
_cpConstraints.push_back(joint); _cpConstraints.push_back(joint);
@ -430,7 +430,7 @@ float PhysicsJointSpring::getRestLength() const
void PhysicsJointSpring::setRestLength(float restLength) void PhysicsJointSpring::setRestLength(float restLength)
{ {
cpDampedSpringSetRestLength(_cpConstraints.front(), PhysicsHelper::float2cpfloat(restLength)); cpDampedSpringSetRestLength(_cpConstraints.front(), restLength);
} }
float PhysicsJointSpring::getStiffness() const float PhysicsJointSpring::getStiffness() const
@ -440,7 +440,7 @@ float PhysicsJointSpring::getStiffness() const
void PhysicsJointSpring::setStiffness(float stiffness) void PhysicsJointSpring::setStiffness(float stiffness)
{ {
cpDampedSpringSetStiffness(_cpConstraints.front(), PhysicsHelper::float2cpfloat(stiffness)); cpDampedSpringSetStiffness(_cpConstraints.front(), stiffness);
} }
float PhysicsJointSpring::getDamping() const float PhysicsJointSpring::getDamping() const
@ -450,7 +450,7 @@ float PhysicsJointSpring::getDamping() const
void PhysicsJointSpring::setDamping(float damping) 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) PhysicsJointGroove* PhysicsJointGroove::construct(PhysicsBody* a, PhysicsBody* b, const Vec2& grooveA, const Vec2& grooveB, const Vec2& anchr2)
@ -539,9 +539,9 @@ bool PhysicsJointRotarySpring::createConstraints()
do { do {
auto joint = cpDampedRotarySpringNew(_bodyA->getCPBody(), auto joint = cpDampedRotarySpringNew(_bodyA->getCPBody(),
_bodyB->getCPBody(), _bodyB->getCPBody(),
PhysicsHelper::float2cpfloat(_bodyB->getRotation() - _bodyA->getRotation()), _bodyB->getRotation() - _bodyA->getRotation(),
PhysicsHelper::float2cpfloat(_stiffness), _stiffness,
PhysicsHelper::float2cpfloat(_damping)); _damping);
CC_BREAK_IF(joint == nullptr); CC_BREAK_IF(joint == nullptr);
_cpConstraints.push_back(joint); _cpConstraints.push_back(joint);
@ -559,7 +559,7 @@ float PhysicsJointRotarySpring::getRestAngle() const
void PhysicsJointRotarySpring::setRestAngle(float restAngle) void PhysicsJointRotarySpring::setRestAngle(float restAngle)
{ {
cpDampedRotarySpringSetRestAngle(_cpConstraints.front(), PhysicsHelper::float2cpfloat(restAngle)); cpDampedRotarySpringSetRestAngle(_cpConstraints.front(), restAngle);
} }
float PhysicsJointRotarySpring::getStiffness() const float PhysicsJointRotarySpring::getStiffness() const
@ -569,7 +569,7 @@ float PhysicsJointRotarySpring::getStiffness() const
void PhysicsJointRotarySpring::setStiffness(float stiffness) void PhysicsJointRotarySpring::setStiffness(float stiffness)
{ {
cpDampedRotarySpringSetStiffness(_cpConstraints.front(), PhysicsHelper::float2cpfloat(stiffness)); cpDampedRotarySpringSetStiffness(_cpConstraints.front(), stiffness);
} }
float PhysicsJointRotarySpring::getDamping() const float PhysicsJointRotarySpring::getDamping() const
@ -579,7 +579,7 @@ float PhysicsJointRotarySpring::getDamping() const
void PhysicsJointRotarySpring::setDamping(float damping) 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) PhysicsJointRotaryLimit* PhysicsJointRotaryLimit::construct(PhysicsBody* a, PhysicsBody* b, float min, float max)
@ -609,8 +609,8 @@ bool PhysicsJointRotaryLimit::createConstraints()
{ {
auto joint = cpRotaryLimitJointNew(_bodyA->getCPBody(), auto joint = cpRotaryLimitJointNew(_bodyA->getCPBody(),
_bodyB->getCPBody(), _bodyB->getCPBody(),
PhysicsHelper::float2cpfloat(_min), _min,
PhysicsHelper::float2cpfloat(_max)); _max);
CC_BREAK_IF(joint == nullptr); CC_BREAK_IF(joint == nullptr);
_cpConstraints.push_back(joint); _cpConstraints.push_back(joint);
@ -628,7 +628,7 @@ float PhysicsJointRotaryLimit::getMin() const
void PhysicsJointRotaryLimit::setMin(float min) void PhysicsJointRotaryLimit::setMin(float min)
{ {
cpRotaryLimitJointSetMin(_cpConstraints.front(), PhysicsHelper::float2cpfloat(min)); cpRotaryLimitJointSetMin(_cpConstraints.front(), min);
} }
float PhysicsJointRotaryLimit::getMax() const float PhysicsJointRotaryLimit::getMax() const
@ -638,7 +638,7 @@ float PhysicsJointRotaryLimit::getMax() const
void PhysicsJointRotaryLimit::setMax(float max) 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) PhysicsJointRatchet* PhysicsJointRatchet::construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratchet)
@ -663,7 +663,7 @@ bool PhysicsJointRatchet::createConstraints()
{ {
auto joint = cpRatchetJointNew(_bodyA->getCPBody(), auto joint = cpRatchetJointNew(_bodyA->getCPBody(),
_bodyB->getCPBody(), _bodyB->getCPBody(),
PhysicsHelper::float2cpfloat(_phase), _phase,
PhysicsHelper::cpfloat2float(_ratchet)); PhysicsHelper::cpfloat2float(_ratchet));
CC_BREAK_IF(joint == nullptr); CC_BREAK_IF(joint == nullptr);
@ -682,7 +682,7 @@ float PhysicsJointRatchet::getAngle() const
void PhysicsJointRatchet::setAngle(float angle) void PhysicsJointRatchet::setAngle(float angle)
{ {
cpRatchetJointSetAngle(_cpConstraints.front(), PhysicsHelper::float2cpfloat(angle)); cpRatchetJointSetAngle(_cpConstraints.front(), angle);
} }
float PhysicsJointRatchet::getPhase() const float PhysicsJointRatchet::getPhase() const
@ -692,7 +692,7 @@ float PhysicsJointRatchet::getPhase() const
void PhysicsJointRatchet::setPhase(float phase) void PhysicsJointRatchet::setPhase(float phase)
{ {
cpRatchetJointSetPhase(_cpConstraints.front(), PhysicsHelper::float2cpfloat(phase)); cpRatchetJointSetPhase(_cpConstraints.front(), phase);
} }
float PhysicsJointRatchet::getRatchet() const float PhysicsJointRatchet::getRatchet() const
@ -702,7 +702,7 @@ float PhysicsJointRatchet::getRatchet() const
void PhysicsJointRatchet::setRatchet(float ratchet) 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) PhysicsJointGear* PhysicsJointGear::construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratio)
@ -727,8 +727,8 @@ bool PhysicsJointGear::createConstraints()
{ {
auto joint = cpGearJointNew(_bodyA->getCPBody(), auto joint = cpGearJointNew(_bodyA->getCPBody(),
_bodyB->getCPBody(), _bodyB->getCPBody(),
PhysicsHelper::float2cpfloat(_phase), _phase,
PhysicsHelper::float2cpfloat(_ratio)); _ratio);
CC_BREAK_IF(joint == nullptr); CC_BREAK_IF(joint == nullptr);
_cpConstraints.push_back(joint); _cpConstraints.push_back(joint);
@ -746,7 +746,7 @@ float PhysicsJointGear::getPhase() const
void PhysicsJointGear::setPhase(float phase) void PhysicsJointGear::setPhase(float phase)
{ {
cpGearJointSetPhase(_cpConstraints.front(), PhysicsHelper::float2cpfloat(phase)); cpGearJointSetPhase(_cpConstraints.front(), phase);
} }
float PhysicsJointGear::getRatio() const float PhysicsJointGear::getRatio() const
@ -756,7 +756,7 @@ float PhysicsJointGear::getRatio() const
void PhysicsJointGear::setRatio(float ratio) void PhysicsJointGear::setRatio(float ratio)
{ {
cpGearJointSetRatio(_cpConstraints.front(), PhysicsHelper::float2cpfloat(ratio)); cpGearJointSetRatio(_cpConstraints.front(), ratio);
} }
PhysicsJointMotor* PhysicsJointMotor::construct(PhysicsBody* a, PhysicsBody* b, float rate) PhysicsJointMotor* PhysicsJointMotor::construct(PhysicsBody* a, PhysicsBody* b, float rate)
@ -780,7 +780,7 @@ bool PhysicsJointMotor::createConstraints()
{ {
auto joint = cpSimpleMotorNew(_bodyA->getCPBody(), auto joint = cpSimpleMotorNew(_bodyA->getCPBody(),
_bodyB->getCPBody(), _bodyB->getCPBody(),
PhysicsHelper::float2cpfloat(_rate)); _rate);
CC_BREAK_IF(joint == nullptr); CC_BREAK_IF(joint == nullptr);
_cpConstraints.push_back(joint); _cpConstraints.push_back(joint);
@ -798,7 +798,7 @@ float PhysicsJointMotor::getRate() const
void PhysicsJointMotor::setRate(float rate) void PhysicsJointMotor::setRate(float rate)
{ {
cpSimpleMotorSetRate(_cpConstraints.front(), PhysicsHelper::float2cpfloat(rate)); cpSimpleMotorSetRate(_cpConstraints.front(), rate);
} }
NS_CC_END NS_CC_END

View File

@ -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<Node*, ComponentPhysics2d*> 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

View File

@ -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 <vector>
#include <unordered_map>
#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<ComponentPhysics2d*> _components;
// record the owners of components for performance
std::unordered_map<Node*, ComponentPhysics2d*> _owners;
PhysicsWorld *_physicsWorld;
Scene *_scene;
};
/** @} */
/** @} */
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -233,7 +233,7 @@ void PhysicsShape::setDensity(float density)
setMass(PHYSICS_INFINITY); setMass(PHYSICS_INFINITY);
}else if (_area > 0) }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) 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) 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) float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Vec2& offset)
{ {
return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), : PhysicsHelper::cpfloat2float(cpMomentForCircle(mass,
0, 0,
PhysicsHelper::float2cpfloat(radius), radius,
PhysicsHelper::point2cpv(offset))); PhysicsHelper::point2cpv(offset)));
} }
@ -375,7 +375,7 @@ float PhysicsShapeCircle::calculateDefaultMoment()
auto shape = _cpShapes.front(); auto shape = _cpShapes.front();
return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), : PhysicsHelper::cpfloat2float(cpMomentForCircle(_mass,
0, 0,
cpCircleShapeGetRadius(shape), cpCircleShapeGetRadius(shape),
cpCircleShapeGetOffset(shape))); cpCircleShapeGetOffset(shape)));
@ -393,11 +393,11 @@ Vec2 PhysicsShapeCircle::getOffset()
void PhysicsShapeCircle::updateScale() void PhysicsShapeCircle::updateScale()
{ {
cpFloat factor = std::abs(PhysicsHelper::float2cpfloat(_newScaleX / _scaleX)); cpFloat factor = std::abs(_newScaleX / _scaleX);
cpShape* shape = _cpShapes.front(); cpShape* shape = _cpShapes.front();
cpVect v = cpCircleShapeGetOffset(shape); cpVect v = cpCircleShapeGetOffset(shape);
v = cpvmult(v, PhysicsHelper::float2cpfloat(factor)); v = cpvmult(v, factor);
((cpCircleShape*)shape)->c = v; ((cpCircleShape*)shape)->c = v;
cpCircleShapeSetRadius(shape, cpCircleShapeGetRadius(shape) * factor); 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, auto shape = cpSegmentShapeNew(s_sharedBody,
PhysicsHelper::point2cpv(a), PhysicsHelper::point2cpv(a),
PhysicsHelper::point2cpv(b), PhysicsHelper::point2cpv(b),
PhysicsHelper::float2cpfloat(border)); border);
CC_BREAK_IF(shape == nullptr); CC_BREAK_IF(shape == nullptr);
@ -464,8 +464,8 @@ Vec2 PhysicsShapeEdgeSegment::getCenter()
void PhysicsShapeEdgeSegment::updateScale() void PhysicsShapeEdgeSegment::updateScale()
{ {
cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); cpFloat factorX = _newScaleX / _scaleX;
cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); cpFloat factorY = _newScaleY / _scaleY;
cpShape* shape = _cpShapes.front(); cpShape* shape = _cpShapes.front();
cpVect a = cpSegmentShapeGetA(shape); cpVect a = cpSegmentShapeGetA(shape);
@ -628,8 +628,8 @@ Vec2 PhysicsShapePolygon::getCenter()
void PhysicsShapePolygon::updateScale() void PhysicsShapePolygon::updateScale()
{ {
cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); cpFloat factorX = _newScaleX / _scaleX;
cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); cpFloat factorY = _newScaleY / _scaleY;
auto shape = _cpShapes.front(); auto shape = _cpShapes.front();
int count = cpPolyShapeGetNumVerts(shape); int count = cpPolyShapeGetNumVerts(shape);
@ -697,8 +697,7 @@ bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material
int i = 0; int i = 0;
for (; i < 4; ++i) for (; i < 4; ++i)
{ {
auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % 4], auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % 4], border);
PhysicsHelper::float2cpfloat(border));
CC_BREAK_IF(shape == nullptr); CC_BREAK_IF(shape == nullptr);
addShape(shape); addShape(shape);
} }
@ -742,8 +741,7 @@ bool PhysicsShapeEdgePolygon::init(const Vec2* points, int count, const PhysicsM
int i = 0; int i = 0;
for (; i < count; ++i) for (; i < count; ++i)
{ {
auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % count], auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[(i + 1) % count], border);
PhysicsHelper::float2cpfloat(border));
CC_BREAK_IF(shape == nullptr); CC_BREAK_IF(shape == nullptr);
cpShapeSetElasticity(shape, 1.0f); cpShapeSetElasticity(shape, 1.0f);
cpShapeSetFriction(shape, 1.0f); cpShapeSetFriction(shape, 1.0f);
@ -812,8 +810,8 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(const Vec2* points, int cou
void PhysicsShapeEdgePolygon::updateScale() void PhysicsShapeEdgePolygon::updateScale()
{ {
cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); cpFloat factorX = _newScaleX / _scaleX;
cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); cpFloat factorY = _newScaleY / _scaleY;
for (auto shape : _cpShapes) for (auto shape : _cpShapes)
{ {
@ -842,8 +840,7 @@ bool PhysicsShapeEdgeChain::init(const Vec2* points, int count, const PhysicsMat
int i = 0; int i = 0;
for (; i < count - 1; ++i) for (; i < count - 1; ++i)
{ {
auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[i + 1], auto shape = cpSegmentShapeNew(s_sharedBody, vec[i], vec[i + 1], border);
PhysicsHelper::float2cpfloat(border));
CC_BREAK_IF(shape == nullptr); CC_BREAK_IF(shape == nullptr);
cpShapeSetElasticity(shape, 1.0f); cpShapeSetElasticity(shape, 1.0f);
cpShapeSetFriction(shape, 1.0f); cpShapeSetFriction(shape, 1.0f);
@ -901,8 +898,8 @@ int PhysicsShapeEdgeChain::getPointsCount() const
void PhysicsShapeEdgeChain::updateScale() void PhysicsShapeEdgeChain::updateScale()
{ {
cpFloat factorX = PhysicsHelper::float2cpfloat(_newScaleX / _scaleX); cpFloat factorX = _newScaleX / _scaleX;
cpFloat factorY = PhysicsHelper::float2cpfloat(_newScaleY / _scaleY); cpFloat factorY = _newScaleY / _scaleY;
for (auto shape : _cpShapes) for (auto shape : _cpShapes)
{ {

View File

@ -281,7 +281,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact)
{ {
contact.setEventCode(PhysicsContact::EventCode::BEGIN); contact.setEventCode(PhysicsContact::EventCode::BEGIN);
contact.setWorld(this); contact.setWorld(this);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); _eventDispatcher->dispatchEvent(&contact);
} }
return ret ? contact.resetResult() : false; return ret ? contact.resetResult() : false;
@ -296,7 +296,7 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact)
contact.setEventCode(PhysicsContact::EventCode::PRESOLVE); contact.setEventCode(PhysicsContact::EventCode::PRESOLVE);
contact.setWorld(this); contact.setWorld(this);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); _eventDispatcher->dispatchEvent(&contact);
return contact.resetResult(); return contact.resetResult();
} }
@ -310,7 +310,7 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact)
contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE); contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE);
contact.setWorld(this); contact.setWorld(this);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); _eventDispatcher->dispatchEvent(&contact);
} }
void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact)
@ -322,7 +322,7 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact)
contact.setEventCode(PhysicsContact::EventCode::SEPARATE); contact.setEventCode(PhysicsContact::EventCode::SEPARATE);
contact.setWorld(this); contact.setWorld(this);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&contact); _eventDispatcher->dispatchEvent(&contact);
} }
void PhysicsWorld::rayCast(PhysicsRayCastCallbackFunc func, const Vec2& point1, const Vec2& point2, void* data) 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; 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() bool PhysicsWorld::init()
{ {
do do
@ -561,7 +549,6 @@ void PhysicsWorld::removeBody(PhysicsBody* body)
body->_world = nullptr; body->_world = nullptr;
} }
void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body)
{ {
if (_delayAddBodies.getIndex(body) != CC_INVALID_INDEX) if (_delayAddBodies.getIndex(body) != CC_INVALID_INDEX)
@ -780,7 +767,7 @@ PhysicsBody* PhysicsWorld::getBody(int tag) const
return nullptr; return nullptr;
} }
void PhysicsWorld::setGravity(const Vect& gravity) void PhysicsWorld::setGravity(const Vec2& gravity)
{ {
_gravity = gravity; _gravity = gravity;
cpSpaceSetGravity(_cpSpace, PhysicsHelper::point2cpv(gravity)); cpSpaceSetGravity(_cpSpace, PhysicsHelper::point2cpv(gravity));
@ -821,6 +808,9 @@ void PhysicsWorld::update(float delta, bool userCall/* = false*/)
updateBodies(); updateBodies();
} }
auto sceneToWorldTransform = _scene->getNodeToParentTransform();
beforeSimulation(_scene, sceneToWorldTransform, 1.f, 1.f, 0.f);
if (!_delayAddJoints.empty() || !_delayRemoveJoints.empty()) if (!_delayAddJoints.empty() || !_delayRemoveJoints.empty())
{ {
updateJoints(); updateJoints();
@ -862,6 +852,24 @@ void PhysicsWorld::update(float delta, bool userCall/* = false*/)
{ {
debugDraw(); 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() PhysicsWorld::PhysicsWorld()
@ -877,6 +885,7 @@ PhysicsWorld::PhysicsWorld()
, _autoStep(true) , _autoStep(true)
, _debugDraw(nullptr) , _debugDraw(nullptr)
, _debugDrawMask(DEBUGDRAW_NONE) , _debugDrawMask(DEBUGDRAW_NONE)
, _eventDispatcher(nullptr)
{ {
} }
@ -892,6 +901,40 @@ PhysicsWorld::~PhysicsWorld()
CC_SAFE_DELETE(_debugDraw); 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) PhysicsDebugDraw::PhysicsDebugDraw(PhysicsWorld& world)
: _drawNode(nullptr) : _drawNode(nullptr)
, _world(world) , _world(world)

View File

@ -28,11 +28,10 @@
#include "base/ccConfig.h" #include "base/ccConfig.h"
#if CC_USE_PHYSICS #if CC_USE_PHYSICS
#include <list>
#include "base/CCVector.h" #include "base/CCVector.h"
#include "base/CCRef.h"
#include "math/CCGeometry.h" #include "math/CCGeometry.h"
#include "physics/CCPhysicsBody.h" #include "physics/CCPhysicsBody.h"
#include <list>
struct cpSpace; struct cpSpace;
@ -43,14 +42,13 @@ class PhysicsJoint;
class PhysicsShape; class PhysicsShape;
class PhysicsContact; class PhysicsContact;
typedef Vec2 Vect;
class Director; class Director;
class Node; class Node;
class Sprite; class Sprite;
class Scene; class Scene;
class DrawNode; class DrawNode;
class PhysicsDebugDraw; class PhysicsDebugDraw;
class EventDispatcher;
class PhysicsWorld; class PhysicsWorld;
@ -60,7 +58,7 @@ typedef struct PhysicsRayCastInfo
Vec2 start; Vec2 start;
Vec2 end; //< in lua, it's name is "ended" Vec2 end; //< in lua, it's name is "ended"
Vec2 contact; Vec2 contact;
Vect normal; Vec2 normal;
float fraction; float fraction;
void* data; void* data;
}PhysicsRayCastInfo; }PhysicsRayCastInfo;
@ -228,16 +226,16 @@ public:
/** /**
* Get the gravity value of this physics world. * 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. * set the gravity value of this physics world.
* *
* @param gravity A 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. * Set the speed of this physics world.
@ -329,7 +327,7 @@ public:
void step(float delta); void step(float delta);
protected: protected:
static PhysicsWorld* construct(); static PhysicsWorld* construct(Scene* scene);
bool init(); bool init();
@ -354,7 +352,7 @@ protected:
virtual void updateJoints(); virtual void updateJoints();
protected: protected:
Vect _gravity; Vec2 _gravity;
float _speed; float _speed;
int _updateRate; int _updateRate;
int _updateRateCount; int _updateRateCount;
@ -371,7 +369,8 @@ protected:
PhysicsDebugDraw* _debugDraw; PhysicsDebugDraw* _debugDraw;
int _debugDrawMask; int _debugDrawMask;
EventDispatcher* _eventDispatcher;
Vector<PhysicsBody*> _delayAddBodies; Vector<PhysicsBody*> _delayAddBodies;
Vector<PhysicsBody*> _delayRemoveBodies; Vector<PhysicsBody*> _delayRemoveBodies;
std::vector<PhysicsJoint*> _delayAddJoints; std::vector<PhysicsJoint*> _delayAddJoints;
@ -381,6 +380,9 @@ protected:
PhysicsWorld(); PhysicsWorld();
virtual ~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 Node;
friend class Sprite; friend class Sprite;
friend class Scene; friend class Scene;
@ -390,7 +392,6 @@ protected:
friend class PhysicsJoint; friend class PhysicsJoint;
friend class PhysicsWorldCallback; friend class PhysicsWorldCallback;
friend class PhysicsDebugDraw; friend class PhysicsDebugDraw;
friend class PhysicsManager;
}; };
/** A physics helper class. Draw physics shape, joint in debug mode. /** A physics helper class. Draw physics shape, joint in debug mode.

View File

@ -6,6 +6,4 @@ set(COCOS_PHYSICS_SRC
physics/CCPhysicsJoint.cpp physics/CCPhysicsJoint.cpp
physics/CCPhysicsShape.cpp physics/CCPhysicsShape.cpp
physics/CCPhysicsWorld.cpp physics/CCPhysicsWorld.cpp
physics/CCComponentPhysics2d.cpp
physics/CCPhysicsManager.cpp
) )

View File

@ -4,7 +4,6 @@
#include <cmath> #include <cmath>
#include "ui/CocosGUI.h" #include "ui/CocosGUI.h"
#include "physics/CCComponentPhysics2d.h"
#include "../testResource.h" #include "../testResource.h"
USING_NS_CC; USING_NS_CC;
@ -98,8 +97,7 @@ Sprite* PhysicsDemo::addGrossiniAtPosition(Vec2 p, float scale/* = 1.0*/)
sp->setScale(scale); sp->setScale(scale);
sp->setPosition(p); sp->setPosition(p);
addPhysicsComponent(sp, PhysicsBody::createBox(Size(48.0f, 108.0f))); sp->addComponent(PhysicsBody::createBox(Size(48.0f, 108.0f)));
//addPhysicsComponent(sp, PhysicsBody::createCircle(sp->getContentSize().height/2));
this->addChild(sp); this->addChild(sp);
return sp; return sp;
@ -173,7 +171,7 @@ Sprite* PhysicsDemo::makeBall(Vec2 point, float radius, PhysicsMaterial material
ball->setScale(0.13f * radius); 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)); ball->setPosition(Vec2(point.x, point.y));
return ball; return ball;
@ -195,7 +193,7 @@ Sprite* PhysicsDemo::makeBox(Vec2 point, Size size, int color, PhysicsMaterial m
box->setScaleX(size.width / 100.0f); box->setScaleX(size.width / 100.0f);
box->setScaleY(size.height / 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)); 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) }; 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)); triangle->setPosition(Vec2(point.x, point.y));
return triangle; return triangle;
@ -254,7 +252,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event)
Node* mouse = Node::create(); Node* mouse = Node::create();
auto physicsBody = PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY); auto physicsBody = PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY);
physicsBody->setDynamic(false); physicsBody->setDynamic(false);
addPhysicsComponent(mouse, physicsBody); mouse->addComponent(physicsBody);
mouse->setPosition(location); mouse->setPosition(location);
this->addChild(mouse); this->addChild(mouse);
PhysicsJointPin* joint = PhysicsJointPin::construct(physicsBody, body, location); 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 // Implementation of PhysicsComponentDemoLogoSmash
void PhysicsDemoLogoSmash::onEnter() void PhysicsDemoLogoSmash::onEnter()
@ -320,7 +311,7 @@ void PhysicsDemoLogoSmash::onEnter()
2*(LOGO_HEIGHT-y + yJitter) + VisibleRect::getVisibleRect().size.height/2 - LOGO_HEIGHT/2), 2*(LOGO_HEIGHT-y + yJitter) + VisibleRect::getVisibleRect().size.height/2 - LOGO_HEIGHT/2),
0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f));
auto physicsBody = ball->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto physicsBody = ball->getPhysicsBody();
physicsBody->setMass(1.0); physicsBody->setMass(1.0);
physicsBody->setMoment(PHYSICS_INFINITY); physicsBody->setMoment(PHYSICS_INFINITY);
@ -331,7 +322,7 @@ void PhysicsDemoLogoSmash::onEnter()
auto bullet = makeBall(Vec2(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); auto bullet = makeBall(Vec2(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0));
bullet->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(Vec2(200, 0)); bullet->getPhysicsBody()->setVelocity(Vec2(200, 0));
bullet->setPosition(Vec2(-500, VisibleRect::getVisibleRect().size.height/2)); bullet->setPosition(Vec2(-500, VisibleRect::getVisibleRect().size.height/2));
@ -363,7 +354,7 @@ void PhysicsDemoClickAdd::onEnter()
_eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this);
auto node = Node::create(); auto node = Node::create();
addPhysicsComponent(node, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); node->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size));
node->setPosition(VisibleRect::center()); node->setPosition(VisibleRect::center());
this->addChild(node); this->addChild(node);
@ -416,14 +407,16 @@ void PhysicsDemoPyramidStack::onEnter()
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto node = Node::create(); 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); this->addChild(node);
auto ball = Sprite::create("Images/ball.png"); auto ball = Sprite::create("Images/ball.png");
ball->setScale(1); ball->setScale(1);
ball->setTag(100); ball->setTag(100);
addPhysicsComponent(ball, PhysicsBody::createCircle(10)); auto body = PhysicsBody::createCircle(10);
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); ball->addComponent(body);
body->setTag(DRAG_BODYS_TAG);
ball->setPosition(VisibleRect::bottom() + Vec2(0, 60)); ball->setPosition(VisibleRect::bottom() + Vec2(0, 60));
this->addChild(ball); this->addChild(ball);
@ -434,7 +427,7 @@ void PhysicsDemoPyramidStack::onEnter()
for (int j = 0; j <= i; j++) for (int j = 0; j <= i; j++)
{ {
auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Vec2((i / 2 - j) * 11, (14 - i) * 23 + 100), 0.2f); auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Vec2((i / 2 - j) * 11, (14 - i) * 23 + 100), 0.2f);
sp->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); sp->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
} }
} }
} }
@ -468,7 +461,7 @@ void PhysicsDemoRayCast::onEnter()
_physicsWorld->setGravity(Point::ZERO); _physicsWorld->setGravity(Point::ZERO);
auto node = DrawNode::create(); 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); node->drawSegment(VisibleRect::leftBottom() + Vec2(0, 50), VisibleRect::rightBottom() + Vec2(0, 50), 1, STATIC_COLOR);
this->addChild(node); this->addChild(node);
@ -632,7 +625,7 @@ std::string PhysicsDemoRayCast::title() const
void PhysicsDemoActions::onEnter() void PhysicsDemoActions::onEnter()
{ {
PhysicsDemo::onEnter(); PhysicsDemo::onEnter();
_physicsWorld->setGravity(Vect::ZERO); _physicsWorld->setGravity(Vec2::ZERO);
auto touchListener = EventListenerTouchOneByOne::create(); auto touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoActions::onTouchBegan, this); touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoActions::onTouchBegan, this);
@ -641,7 +634,7 @@ void PhysicsDemoActions::onEnter()
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto node = Node::create(); auto node = Node::create();
addPhysicsComponent(node, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); node->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size));
node->setPosition(VisibleRect::center()); node->setPosition(VisibleRect::center());
this->addChild(node); this->addChild(node);
@ -649,12 +642,12 @@ void PhysicsDemoActions::onEnter()
Sprite* sp2 = addGrossiniAtPosition(VisibleRect::left() + Vec2(50, 0)); Sprite* sp2 = addGrossiniAtPosition(VisibleRect::left() + Vec2(50, 0));
Sprite* sp3 = addGrossiniAtPosition(VisibleRect::right() - Vec2(20, 0)); Sprite* sp3 = addGrossiniAtPosition(VisibleRect::right() - Vec2(20, 0));
Sprite* sp4 = addGrossiniAtPosition(VisibleRect::leftTop() + Vec2(50, -50)); Sprite* sp4 = addGrossiniAtPosition(VisibleRect::leftTop() + Vec2(50, -50));
sp4->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setGravityEnable(false); sp4->getPhysicsBody()->setGravityEnable(false);
sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
sp3->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); sp3->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
sp4->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); sp4->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
auto actionTo = JumpTo::create(2, Vec2(100, 100), 50, 4); auto actionTo = JumpTo::create(2, Vec2(100, 100), 50, 4);
auto actionBy = JumpBy::create(2, Vec2(300, 0), 50, 4); auto actionBy = JumpBy::create(2, Vec2(300, 0), 50, 4);
@ -693,7 +686,7 @@ void PhysicsDemoJoints::onEnter()
Node* node = Node::create(); Node* node = Node::create();
PhysicsBody* box = PhysicsBody::create(); PhysicsBody* box = PhysicsBody::create();
addPhysicsComponent(node, box); node->addComponent(box);
box->setDynamic(false); box->setDynamic(false);
node->setPosition(Point::ZERO); node->setPosition(Point::ZERO);
@ -711,11 +704,11 @@ void PhysicsDemoJoints::onEnter()
case 0: case 0:
{ {
auto sp1 = makeBall(offset - Vec2(30, 0), 10); auto sp1 = makeBall(offset - Vec2(30, 0), 10);
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBall(offset + Vec2(30, 0), 10); auto sp2 = makeBall(offset + Vec2(30, 0), 10);
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
PhysicsJointPin* joint = PhysicsJointPin::construct(sp1PhysicsBody, sp2PhysicsBody, offset); PhysicsJointPin* joint = PhysicsJointPin::construct(sp1PhysicsBody, sp2PhysicsBody, offset);
@ -729,11 +722,11 @@ void PhysicsDemoJoints::onEnter()
{ {
auto sp1 = makeBall(offset - Vec2(30, 0), 10); auto sp1 = makeBall(offset - Vec2(30, 0), 10);
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
PhysicsJointFixed* joint = PhysicsJointFixed::construct(sp1PhysicsBody, sp2PhysicsBody, offset); PhysicsJointFixed* joint = PhysicsJointFixed::construct(sp1PhysicsBody, sp2PhysicsBody, offset);
@ -746,11 +739,11 @@ void PhysicsDemoJoints::onEnter()
case 2: case 2:
{ {
auto sp1 = makeBall(offset - Vec2(30, 0), 10); auto sp1 = makeBall(offset - Vec2(30, 0), 10);
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
PhysicsJointDistance* joint = PhysicsJointDistance::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO); PhysicsJointDistance* joint = PhysicsJointDistance::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO);
@ -763,11 +756,11 @@ void PhysicsDemoJoints::onEnter()
case 3: case 3:
{ {
auto sp1 = makeBall(offset - Vec2(30, 0), 10); auto sp1 = makeBall(offset - Vec2(30, 0), 10);
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
PhysicsJointLimit* joint = PhysicsJointLimit::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO, 30.0f, 60.0f); PhysicsJointLimit* joint = PhysicsJointLimit::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO, 30.0f, 60.0f);
@ -780,11 +773,11 @@ void PhysicsDemoJoints::onEnter()
case 4: case 4:
{ {
auto sp1 = makeBall(offset - Vec2(30, 0), 10); auto sp1 = makeBall(offset - Vec2(30, 0), 10);
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
PhysicsJointSpring* joint = PhysicsJointSpring::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO, 500.0f, 0.3f); PhysicsJointSpring* joint = PhysicsJointSpring::construct(sp1PhysicsBody, sp2PhysicsBody, Point::ZERO, Point::ZERO, 500.0f, 0.3f);
@ -797,11 +790,11 @@ void PhysicsDemoJoints::onEnter()
case 5: case 5:
{ {
auto sp1 = makeBall(offset - Vec2(30, 0), 10); auto sp1 = makeBall(offset - Vec2(30, 0), 10);
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
PhysicsJointGroove* joint = PhysicsJointGroove::construct(sp1PhysicsBody, sp2PhysicsBody, Vec2(30, 15), Vec2(30, -15), Vec2(-30, 0)); PhysicsJointGroove* joint = PhysicsJointGroove::construct(sp1PhysicsBody, sp2PhysicsBody, Vec2(30, 15), Vec2(30, -15), Vec2(-30, 0));
@ -814,11 +807,11 @@ void PhysicsDemoJoints::onEnter()
case 6: case 6:
{ {
auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10));
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition()));
@ -833,11 +826,11 @@ void PhysicsDemoJoints::onEnter()
case 7: case 7:
{ {
auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10));
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition()));
@ -852,11 +845,11 @@ void PhysicsDemoJoints::onEnter()
case 8: case 8:
{ {
auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10));
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition()));
@ -871,11 +864,11 @@ void PhysicsDemoJoints::onEnter()
case 9: case 9:
{ {
auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10));
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition()));
@ -890,11 +883,11 @@ void PhysicsDemoJoints::onEnter()
case 10: case 10:
{ {
auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10)); auto sp1 = makeBox(offset - Vec2(30, 0), Size(30, 10));
auto sp1PhysicsBody = sp1->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp1PhysicsBody = sp1->getPhysicsBody();
sp1PhysicsBody->setTag(DRAG_BODYS_TAG); sp1PhysicsBody->setTag(DRAG_BODYS_TAG);
auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10)); auto sp2 = makeBox(offset + Vec2(30, 0), Size(30, 10));
auto sp2PhysicsBody = sp2->getComponent<ComponentPhysics2d>()->getPhysicsBody(); auto sp2PhysicsBody = sp2->getPhysicsBody();
sp2PhysicsBody->setTag(DRAG_BODYS_TAG); sp2PhysicsBody->setTag(DRAG_BODYS_TAG);
getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition())); getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1PhysicsBody, box, sp1->getPosition()));
@ -933,19 +926,20 @@ void PhysicsDemoPump::onEnter()
scheduleUpdate(); scheduleUpdate();
auto node = Node::create(); auto node = Node::create();
addPhysicsComponent(node, PhysicsBody::create()); auto nodeBody = PhysicsBody::create();
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setDynamic(false); node->addComponent(nodeBody);
nodeBody->setDynamic(false);
PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f);
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, 0), VisibleRect::leftTop() + Vec2(50, -130), staticMaterial, 2.0f)); nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, 0), VisibleRect::leftTop() + Vec2(50, -130), staticMaterial, 2.0f));
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(190, 0), VisibleRect::leftTop() + Vec2(100, -50), staticMaterial, 2.0f)); nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(190, 0), VisibleRect::leftTop() + Vec2(100, -50), staticMaterial, 2.0f));
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -50), VisibleRect::leftTop() + Vec2(100, -90), staticMaterial, 2.0f)); nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -50), VisibleRect::leftTop() + Vec2(100, -90), staticMaterial, 2.0f));
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, -130), VisibleRect::leftTop() + Vec2(100, -145), staticMaterial, 2.0f)); nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(50, -130), VisibleRect::leftTop() + Vec2(100, -145), staticMaterial, 2.0f));
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -145), VisibleRect::leftBottom() + Vec2(100, 80), staticMaterial, 2.0f)); nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(100, -145), VisibleRect::leftBottom() + Vec2(100, 80), staticMaterial, 2.0f));
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->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::leftBottom() + Vec2(150, 80), staticMaterial, 2.0f));
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(150, -80), VisibleRect::rightTop() + Vec2(-100, -150), staticMaterial, 2.0f)); nodeBody->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Vec2(150, -80), VisibleRect::rightTop() + Vec2(-100, -150), staticMaterial, 2.0f));
node->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x01); nodeBody->setCategoryBitmask(0x01);
node->setPosition(Vec2::ZERO); node->setPosition(Vec2::ZERO);
this->addChild(node); this->addChild(node);
@ -953,7 +947,7 @@ void PhysicsDemoPump::onEnter()
for (int i = 0; i < 6; ++i) 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)); auto ball = makeBall(VisibleRect::leftTop() + Vec2(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.05f, 0.0f, 0.1f));
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
addChild(ball); addChild(ball);
} }
@ -969,49 +963,55 @@ void PhysicsDemoPump::onEnter()
auto pump = Node::create(); auto pump = Node::create();
auto center = PhysicsShape::getPolyonCenter(vec, 4); auto center = PhysicsShape::getPolyonCenter(vec, 4);
pump->setPosition(center); 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); this->addChild(pump);
pump->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x02); pumpBody->setCategoryBitmask(0x02);
pump->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setGravityEnable(false); 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(); auto sgear = Node::create();
addPhysicsComponent(sgear, PhysicsBody::createCircle(44)); sgear->addComponent(sgearBody);
sgear->setPosition(VisibleRect::leftBottom() + Vec2(125, 0)); sgear->setPosition(VisibleRect::leftBottom() + Vec2(125, 0));
this->addChild(sgear); this->addChild(sgear);
sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x04);
sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCollisionBitmask(0x04);
sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(1);
_physicsWorld->addJoint(PhysicsJointPin::construct(node->getComponent<ComponentPhysics2d>()->getPhysicsBody(), sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody(), sgear->getPosition())); _physicsWorld->addJoint(PhysicsJointPin::construct(nodeBody, sgearBody, sgear->getPosition()));
_physicsWorld->addJoint(PhysicsJointDistance::construct(pump->getComponent<ComponentPhysics2d>()->getPhysicsBody(), sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody(), Vec2(0, 0), Vec2(0, -44))); _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(); auto bgear = Node::create();
addPhysicsComponent(bgear, PhysicsBody::createCircle(100)); bgear->addComponent(bgearBody);
bgear->setPosition(VisibleRect::leftBottom() + Vec2(275, 0)); bgear->setPosition(VisibleRect::leftBottom() + Vec2(275, 0));
this->addChild(bgear); this->addChild(bgear);
bgear->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x04);
_physicsWorld->addJoint(PhysicsJointPin::construct(bgear->getComponent<ComponentPhysics2d>()->getPhysicsBody(), node->getComponent<ComponentPhysics2d>()->getPhysicsBody(), bgear->getPosition())); _physicsWorld->addJoint(PhysicsJointPin::construct(bgearBody, nodeBody, bgear->getPosition()));
_physicsWorld->addJoint(PhysicsJointGear::construct(sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody(), bgear->getComponent<ComponentPhysics2d>()->getPhysicsBody(), (float)-M_PI_2, -2.0f)); _physicsWorld->addJoint(PhysicsJointGear::construct(sgearBody, bgearBody, (float)-M_PI_2, -2.0f));
// plugger // plugger
Vec2 seg[] = { VisibleRect::leftTop() + Vec2(75, -120), VisibleRect::leftBottom() + Vec2(75, -100) }; Vec2 seg[] = { VisibleRect::leftTop() + Vec2(75, -120), VisibleRect::leftBottom() + Vec2(75, -100) };
Vec2 segCenter = (seg[1] + seg[0]) / 2; Vec2 segCenter = (seg[1] + seg[0]) / 2;
seg[1] -= segCenter; seg[1] -= segCenter;
seg[0] -= 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(); auto plugger = Node::create();
addPhysicsComponent(plugger, PhysicsBody::createEdgeSegment(seg[0], seg[1], PhysicsMaterial(0.01f, 0.0f, 0.5f), 20)); plugger->addComponent(pluggerBody);
plugger->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setDynamic(true);
plugger->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setMass(30);
plugger->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setMoment(100000);
plugger->setPosition(segCenter); plugger->setPosition(segCenter);
this->addChild(plugger); this->addChild(plugger);
plugger->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x02);
sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCollisionBitmask(0x04 | 0x01); sgearBody->setCollisionBitmask(0x04 | 0x01);
_physicsWorld->addJoint(PhysicsJointPin::construct(node->getComponent<ComponentPhysics2d>()->getPhysicsBody(), plugger->getComponent<ComponentPhysics2d>()->getPhysicsBody(), VisibleRect::leftBottom() + Vec2(75, -90))); _physicsWorld->addJoint(PhysicsJointPin::construct(nodeBody, pluggerBody, VisibleRect::leftBottom() + Vec2(75, -90)));
_physicsWorld->addJoint(PhysicsJointDistance::construct(plugger->getComponent<ComponentPhysics2d>()->getPhysicsBody(), sgear->getComponent<ComponentPhysics2d>()->getPhysicsBody(), Vec2::ZERO, Vec2(44, 0))); _physicsWorld->addJoint(PhysicsJointDistance::construct(pluggerBody, sgearBody, Vec2::ZERO, Vec2(44, 0)));
} }
void PhysicsDemoPump::update(float delta) void PhysicsDemoPump::update(float delta)
@ -1090,22 +1090,25 @@ void PhysicsDemoOneWayPlatform::onEnter()
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto ground = Node::create(); 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); this->addChild(ground);
auto platform = makeBox(VisibleRect::center(), Size(200, 50)); auto platform = makeBox(VisibleRect::center(), Size(200, 50));
platform->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setDynamic(false); auto platformBody = platform->getPhysicsBody();
platform->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setContactTestBitmask(0xFFFFFFFF); platformBody->setDynamic(false);
platformBody->setContactTestBitmask(0xFFFFFFFF);
this->addChild(platform); this->addChild(platform);
auto ball = makeBall(VisibleRect::center() - Vec2(0, 50), 20); auto ball = makeBall(VisibleRect::center() - Vec2(0, 50), 20);
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(Vec2(0, 150)); auto ballBody = ball->getPhysicsBody();
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); ballBody->setVelocity(Vec2(0, 150));
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setMass(1.0f); ballBody->setTag(DRAG_BODYS_TAG);
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setContactTestBitmask(0xFFFFFFFF); ballBody->setMass(1.0f);
ballBody->setContactTestBitmask(0xFFFFFFFF);
this->addChild(ball); this->addChild(ball);
auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getComponent<ComponentPhysics2d>()->getPhysicsBody(), ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()); auto contactListener = EventListenerPhysicsContactWithBodies::create(platformBody, ballBody);
contactListener->onContactBegin = CC_CALLBACK_1(PhysicsDemoOneWayPlatform::onContactBegin, this); contactListener->onContactBegin = CC_CALLBACK_1(PhysicsDemoOneWayPlatform::onContactBegin, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
} }
@ -1133,14 +1136,14 @@ void PhysicsDemoSlice::onEnter()
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto ground = Node::create(); 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); this->addChild(ground);
auto box = Node::create(); auto box = Node::create();
Vec2 points[4] = {Vec2(-100, -100), Vec2(-100, 100), Vec2(100, 100), Vec2(100, -100)}; 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->setPosition(VisibleRect::center());
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(_sliceTag); box->getPhysicsBody()->setTag(_sliceTag);
addChild(box); addChild(box);
} }
@ -1199,7 +1202,7 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Vec2 normal, float d
Node* node = Node::create(); Node* node = Node::create();
PhysicsBody* polyon = PhysicsBody::createPolygon(points, pointsCount, PHYSICSBODY_MATERIAL_DEFAULT, -center); PhysicsBody* polyon = PhysicsBody::createPolygon(points, pointsCount, PHYSICSBODY_MATERIAL_DEFAULT, -center);
node->setPosition(center); node->setPosition(center);
addPhysicsComponent(node, polyon); node->addComponent(polyon);
polyon->setVelocity(body->getVelocityAtWorldPoint(center)); polyon->setVelocity(body->getVelocityAtWorldPoint(center));
polyon->setAngularVelocity(body->getAngularVelocity()); polyon->setAngularVelocity(body->getAngularVelocity());
polyon->setTag(_sliceTag); polyon->setTag(_sliceTag);
@ -1228,7 +1231,7 @@ void PhysicsDemoBug3988::onEnter()
{ {
PhysicsDemo::onEnter(); PhysicsDemo::onEnter();
toggleDebug(); toggleDebug();
_physicsWorld->setGravity(Vect::ZERO); _physicsWorld->setGravity(Vec2::ZERO);
auto ball = Sprite::create("Images/YellowSquare.png"); auto ball = Sprite::create("Images/YellowSquare.png");
ball->setPosition(VisibleRect::center() - Vec2(100, 0)); ball->setPosition(VisibleRect::center() - Vec2(100, 0));
@ -1253,7 +1256,7 @@ std::string PhysicsDemoBug3988::subtitle() const
void PhysicsContactTest::onEnter() void PhysicsContactTest::onEnter()
{ {
PhysicsDemo::onEnter(); PhysicsDemo::onEnter();
_physicsWorld->setGravity(Vect::ZERO); _physicsWorld->setGravity(Vec2::ZERO);
auto s = VisibleRect::getVisibleRect().size; auto s = VisibleRect::getVisibleRect().size;
_yellowBoxNum = 50; _yellowBoxNum = 50;
@ -1410,7 +1413,7 @@ void PhysicsContactTest::resetTest()
label->setPosition(Vec2(s.width / 2, s.height - 170)); label->setPosition(Vec2(s.width / 2, s.height - 170));
auto wall = Node::create(); 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()); wall->setPosition(VisibleRect::center());
root->addChild(wall); root->addChild(wall);
@ -1427,12 +1430,13 @@ void PhysicsContactTest::resetTest()
position.x = position.x * CCRANDOM_0_1(); position.x = position.x * CCRANDOM_0_1();
position.y = position.y * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1();
position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); 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)); auto box = makeBox(position, size, 1, PhysicsMaterial(0.1f, 1, 0.0f));
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(velocity); auto boxBody = box->getPhysicsBody();
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x01); // 0001 boxBody->setVelocity(velocity);
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setContactTestBitmask(0x04); // 0100 boxBody->setCategoryBitmask(0x01); // 0001
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCollisionBitmask(0x03); // 0011 boxBody->setContactTestBitmask(0x04); // 0100
boxBody->setCollisionBitmask(0x03); // 0011
root->addChild(box); root->addChild(box);
} }
@ -1445,12 +1449,13 @@ void PhysicsContactTest::resetTest()
position.x = position.x * CCRANDOM_0_1(); position.x = position.x * CCRANDOM_0_1();
position.y = position.y * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1();
position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); 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)); auto box = makeBox(position, size, 2, PhysicsMaterial(0.1f, 1, 0.0f));
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(velocity); auto boxBody = box->getPhysicsBody();
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x02); // 0010 boxBody->setVelocity(velocity);
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setContactTestBitmask(0x08); // 1000 boxBody->setCategoryBitmask(0x02); // 0010
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCollisionBitmask(0x01); // 0001 boxBody->setContactTestBitmask(0x08); // 1000
boxBody->setCollisionBitmask(0x01); // 0001
root->addChild(box); root->addChild(box);
} }
@ -1463,12 +1468,13 @@ void PhysicsContactTest::resetTest()
position.x = position.x * CCRANDOM_0_1(); position.x = position.x * CCRANDOM_0_1();
position.y = position.y * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1();
position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); 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)); auto triangle = makeTriangle(position, size, 1, PhysicsMaterial(0.1f, 1, 0.0f));
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(velocity); auto triangleBody = triangle->getPhysicsBody();
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x04); // 0100 triangleBody->setVelocity(velocity);
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setContactTestBitmask(0x01); // 0001 triangleBody->setCategoryBitmask(0x04); // 0100
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCollisionBitmask(0x06); // 0110 triangleBody->setContactTestBitmask(0x01); // 0001
triangleBody->setCollisionBitmask(0x06); // 0110
root->addChild(triangle); root->addChild(triangle);
} }
@ -1481,12 +1487,13 @@ void PhysicsContactTest::resetTest()
position.x = position.x * CCRANDOM_0_1(); position.x = position.x * CCRANDOM_0_1();
position.y = position.y * CCRANDOM_0_1(); position.y = position.y * CCRANDOM_0_1();
position = VisibleRect::leftBottom() + position + Vec2(size.width / 2, size.height / 2); 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)); auto triangle = makeTriangle(position, size, 2, PhysicsMaterial(0.1f, 1, 0.0f));
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(velocity); auto triangleBody = triangle->getPhysicsBody();
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCategoryBitmask(0x08); // 1000 triangleBody->setVelocity(velocity);
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setContactTestBitmask(0x02); // 0010 triangleBody->setCategoryBitmask(0x08); // 1000
triangle->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setCollisionBitmask(0x01); // 0001 triangleBody->setContactTestBitmask(0x02); // 0010
triangleBody->setCollisionBitmask(0x01); // 0001
root->addChild(triangle); root->addChild(triangle);
} }
} }
@ -1525,7 +1532,7 @@ void PhysicsPositionRotationTest::onEnter()
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto wall = Node::create(); auto wall = Node::create();
addPhysicsComponent(wall, PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); wall->addComponent(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size));
wall->setPosition(VisibleRect::center()); wall->setPosition(VisibleRect::center());
addChild(wall); addChild(wall);
@ -1534,32 +1541,33 @@ void PhysicsPositionRotationTest::onEnter()
//anchorNode->setAnchorPoint(Vec2(0.1f, 0.9f)); //anchorNode->setAnchorPoint(Vec2(0.1f, 0.9f));
anchorNode->setPosition(100, 100); anchorNode->setPosition(100, 100);
anchorNode->setScale(0.25); anchorNode->setScale(0.25);
addPhysicsComponent(anchorNode, PhysicsBody::createBox(anchorNode->getContentSize())); anchorNode->addComponent(PhysicsBody::createBox(anchorNode->getContentSize()));
anchorNode->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); anchorNode->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
addChild(anchorNode); addChild(anchorNode);
//parent test //parent test
auto parent = Sprite::create("Images/YellowSquare.png"); auto parent = Sprite::create("Images/YellowSquare.png");
parent->setPosition(200, 100); parent->setPosition(200, 100);
parent->setScale(0.25); parent->setScale(0.25);
addPhysicsComponent(parent,PhysicsBody::createBox(parent->getContentSize())); parent->addComponent(PhysicsBody::createBox(parent->getContentSize()));
parent->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); parent->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
addChild(parent); addChild(parent);
auto leftBall = Sprite::create("Images/ball.png"); auto leftBall = Sprite::create("Images/ball.png");
leftBall->setPosition(-30, 0); leftBall->setPosition(-30, 0);
leftBall->Node::setScale(2); leftBall->Node::setScale(2);
addPhysicsComponent(leftBall, PhysicsBody::createCircle(leftBall->getContentSize().width/2)); leftBall->addComponent(PhysicsBody::createCircle(leftBall->getContentSize().width/2));
leftBall->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); leftBall->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
parent->addChild(leftBall); parent->addChild(leftBall);
// offset position rotation test // offset position rotation test
auto offsetPosNode = Sprite::create("Images/YellowSquare.png"); auto offsetPosNode = Sprite::create("Images/YellowSquare.png");
offsetPosNode->setPosition(100, 200); offsetPosNode->setPosition(100, 200);
addPhysicsComponent(offsetPosNode, PhysicsBody::createBox(offsetPosNode->getContentSize()/2)); auto body = PhysicsBody::createBox(offsetPosNode->getContentSize() / 2);
offsetPosNode->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setPositionOffset(-Vec2(offsetPosNode->getContentSize() / 2)); offsetPosNode->addComponent(body);
offsetPosNode->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setRotationOffset(45); body->setPositionOffset(-Vec2(offsetPosNode->getContentSize() / 2));
offsetPosNode->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); body->setRotationOffset(45);
body->setTag(DRAG_BODYS_TAG);
addChild(offsetPosNode); addChild(offsetPosNode);
return; return;
@ -1582,36 +1590,39 @@ void PhysicsSetGravityEnableTest::onEnter()
// wall // wall
auto wall = Node::create(); 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()); wall->setPosition(VisibleRect::center());
addChild(wall); addChild(wall);
// common box // common box
auto commonBox = makeBox(Vec2(100, 100), Size(50, 50), 1); auto commonBox = makeBox(Vec2(100, 100), Size(50, 50), 1);
commonBox->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); commonBox->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
addChild(commonBox); addChild(commonBox);
auto box = makeBox(Vec2(200, 100), Size(50, 50), 2); auto box = makeBox(Vec2(200, 100), Size(50, 50), 2);
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setMass(20); auto boxBody = box->getPhysicsBody();
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); boxBody->setMass(20);
box->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setGravityEnable(false); boxBody->setTag(DRAG_BODYS_TAG);
boxBody->setGravityEnable(false);
addChild(box); addChild(box);
auto ball = makeBall(Vec2(200, 200), 50); auto ball = makeBall(Vec2(200, 200), 50);
ball->setTag(2); ball->setTag(2);
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); auto ballBody = ball->getPhysicsBody();
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setGravityEnable(false); ballBody->setTag(DRAG_BODYS_TAG);
ballBody->setGravityEnable(false);
ballBody->setMass(50);
addChild(ball); addChild(ball);
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setMass(50);
scheduleOnce(CC_SCHEDULE_SELECTOR(PhysicsSetGravityEnableTest::onScheduleOnce), 1.0); scheduleOnce(CC_SCHEDULE_SELECTOR(PhysicsSetGravityEnableTest::onScheduleOnce), 1.0);
} }
void PhysicsSetGravityEnableTest::onScheduleOnce(float delta) void PhysicsSetGravityEnableTest::onScheduleOnce(float delta)
{ {
auto ball = getChildByTag(2); auto ball = getChildByTag(2);
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setMass(200); ball->getPhysicsBody()->setMass(200);
_physicsWorld->setGravity(Vect(0, 98)); _physicsWorld->setGravity(Vec2(0, 98));
} }
std::string PhysicsSetGravityEnableTest::title() const std::string PhysicsSetGravityEnableTest::title() const
@ -1640,7 +1651,7 @@ void PhysicsDemoBug5482::onEnter()
// wall // wall
auto wall = Node::create(); 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()); wall->setPosition(VisibleRect::center());
addChild(wall); addChild(wall);
@ -1653,12 +1664,10 @@ void PhysicsDemoBug5482::onEnter()
_nodeA = Sprite::create("Images/YellowSquare.png"); _nodeA = Sprite::create("Images/YellowSquare.png");
_nodeA->setPosition(VisibleRect::center().x - 150, 100); _nodeA->setPosition(VisibleRect::center().x - 150, 100);
_nodeA->addComponent(ComponentPhysics2d::create());
this->addChild(_nodeA); this->addChild(_nodeA);
_nodeB = Sprite::create("Images/YellowSquare.png"); _nodeB = Sprite::create("Images/YellowSquare.png");
_nodeB->setPosition(VisibleRect::center().x + 150, 100); _nodeB->setPosition(VisibleRect::center().x + 150, 100);
_nodeB->addComponent(ComponentPhysics2d::create());
this->addChild(_nodeB); this->addChild(_nodeB);
_body = PhysicsBody::createBox(_nodeA->getContentSize()); _body = PhysicsBody::createBox(_nodeA->getContentSize());
@ -1675,7 +1684,11 @@ void PhysicsDemoBug5482::onExit()
void PhysicsDemoBug5482::changeBodyCallback(Ref* sender) void PhysicsDemoBug5482::changeBodyCallback(Ref* sender)
{ {
Sprite* node = _bodyInA ? _nodeB : _nodeA; Sprite* node = _bodyInA ? _nodeB : _nodeA;
node->getComponent<ComponentPhysics2d>()->setPhysicsBody(_body); if (_body->getOwner())
{
_body->getOwner()->removeComponent(_body);
}
node->addComponent(_body);
_bodyInA = !_bodyInA; _bodyInA = !_bodyInA;
} }
@ -1698,7 +1711,7 @@ void PhysicsFixedUpdate::onEnter()
// wall // wall
auto wall = Node::create(); 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()); wall->setPosition(VisibleRect::center());
this->addChild(wall); this->addChild(wall);
@ -1711,9 +1724,10 @@ void PhysicsFixedUpdate::addBall()
{ {
auto ball = Sprite::create("Images/ball.png"); auto ball = Sprite::create("Images/ball.png");
ball->setPosition(100, 100); ball->setPosition(100, 100);
addPhysicsComponent(ball, PhysicsBody::createCircle(ball->getContentSize().width/2, PhysicsMaterial(0.1f, 1, 0.0f))); auto ballBody = PhysicsBody::createCircle(ball->getContentSize().width / 2, PhysicsMaterial(0.1f, 1, 0.0f));
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); ball->addComponent(ballBody);
ball->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(Point(1000, 20)); ballBody->setTag(DRAG_BODYS_TAG);
ballBody->setVelocity(Point(1000, 20));
this->addChild(ball); this->addChild(ball);
} }
@ -1765,7 +1779,7 @@ void PhysicsTransformTest::onEnter()
addChild(_rootLayer); addChild(_rootLayer);
auto wall = Node::create(); 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()); wall->setPosition(VisibleRect::center());
_rootLayer->addChild(wall); _rootLayer->addChild(wall);
@ -1773,16 +1787,16 @@ void PhysicsTransformTest::onEnter()
_parentSprite = Sprite::create("Images/YellowSquare.png"); _parentSprite = Sprite::create("Images/YellowSquare.png");
_parentSprite->setPosition(200, 100); _parentSprite->setPosition(200, 100);
_parentSprite->setScale(0.25); _parentSprite->setScale(0.25);
addPhysicsComponent(_parentSprite, PhysicsBody::createBox(_parentSprite->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f))); _parentSprite->addComponent(PhysicsBody::createBox(_parentSprite->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f)));
_parentSprite->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); _parentSprite->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
_parentSprite->setTag(1); _parentSprite->setTag(1);
_rootLayer->addChild(_parentSprite); _rootLayer->addChild(_parentSprite);
auto leftBall = Sprite::create("Images/ball.png"); auto leftBall = Sprite::create("Images/ball.png");
leftBall->setPosition(-30, 0); leftBall->setPosition(-30, 0);
leftBall->setScale(2); leftBall->setScale(2);
addPhysicsComponent(leftBall, PhysicsBody::createCircle(leftBall->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f))); leftBall->addComponent(PhysicsBody::createCircle(leftBall->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f)));
leftBall->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); leftBall->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
_parentSprite->addChild(leftBall); _parentSprite->addChild(leftBall);
ScaleTo* scaleTo = ScaleTo::create(2.0, 0.5); ScaleTo* scaleTo = ScaleTo::create(2.0, 0.5);
@ -1792,14 +1806,14 @@ void PhysicsTransformTest::onEnter()
auto normal = Sprite::create("Images/YellowSquare.png"); auto normal = Sprite::create("Images/YellowSquare.png");
normal->setPosition(300, 100); normal->setPosition(300, 100);
normal->setScale(0.25, 0.5); normal->setScale(0.25, 0.5);
addPhysicsComponent(normal,PhysicsBody::createBox(normal->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f))); normal->addComponent(PhysicsBody::createBox(normal->getContentSize(), PhysicsMaterial(0.1f, 1.0f, 0.0f)));
normal->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setTag(DRAG_BODYS_TAG); normal->getPhysicsBody()->setTag(DRAG_BODYS_TAG);
_rootLayer->addChild(normal); _rootLayer->addChild(normal);
auto bullet = Sprite::create("Images/ball.png"); auto bullet = Sprite::create("Images/ball.png");
bullet->setPosition(200, 200); bullet->setPosition(200, 200);
addPhysicsComponent(bullet,PhysicsBody::createCircle(bullet->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f))); bullet->addComponent(PhysicsBody::createCircle(bullet->getContentSize().width/2, PhysicsMaterial(0.1f, 1.0f, 0.0f)));
bullet->getComponent<ComponentPhysics2d>()->getPhysicsBody()->setVelocity(Vect(100, 100)); bullet->getPhysicsBody()->setVelocity(Vec2(100, 100));
_rootLayer->addChild(bullet); _rootLayer->addChild(bullet);
MoveBy* move = MoveBy::create(2.0f, Vec2(100, 100)); MoveBy* move = MoveBy::create(2.0f, Vec2(100, 100));

View File

@ -33,7 +33,6 @@ public:
void toggleDebug(); void toggleDebug();
protected: protected:
void addPhysicsComponent(cocos2d::Node *node, cocos2d::PhysicsBody *physicsBody);
cocos2d::Texture2D* _spriteTexture; cocos2d::Texture2D* _spriteTexture;
cocos2d::SpriteBatchNode* _ball; cocos2d::SpriteBatchNode* _ball;

View File

@ -3,7 +3,6 @@ local MATERIAL_DEFAULT = cc.PhysicsMaterial(0.1, 0.5, 0.5)
local curLayer = nil local curLayer = nil
local STATIC_COLOR = cc.c4f(1.0, 0.0, 0.0, 1.0) local STATIC_COLOR = cc.c4f(1.0, 0.0, 0.0, 1.0)
local DRAG_BODYS_TAG = 0x80 local DRAG_BODYS_TAG = 0x80
local PHYSICS_COMPONENT_NAME = "physics_component"
local function range(from, to, step) local function range(from, to, step)
step = step or 1 step = step or 1
@ -44,12 +43,6 @@ local function initWithLayer(layer, callback)
layer:registerScriptHandler(onNodeEvent) layer:registerScriptHandler(onNodeEvent)
end 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) local function addGrossiniAtPosition(layer, p, scale)
scale = scale or 1.0 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)) local sp = cc.Sprite:createWithTexture(layer.spriteTexture, cc.rect(posx, posy, 85, 121))
sp:setScale(scale) sp:setScale(scale)
-- sp:setPhysicsBody(cc.PhysicsBody:createBox(cc.size(48.0*scale, 108.0*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)))
layer:addChild(sp) layer:addChild(sp)
sp:setPosition(p) sp:setPosition(p)
return sp return sp
@ -82,7 +74,7 @@ local function onTouchBegan(touch, event)
if body then if body then
local mouse = cc.Node:create() local mouse = cc.Node:create()
local physicsBody = cc.PhysicsBody:create(PHYSICS_INFINITY, PHYSICS_INFINITY) local physicsBody = cc.PhysicsBody:create(PHYSICS_INFINITY, PHYSICS_INFINITY)
addPhysicsComponent(mouse, physicsBody) mouse:setPhysicsBody(physicsBody)
physicsBody:setDynamic(false) physicsBody:setDynamic(false)
mouse:setPosition(location) mouse:setPosition(location)
curLayer:addChild(mouse) curLayer:addChild(mouse)
@ -123,8 +115,7 @@ local function makeBall(layer, point, radius, material)
ball:setScale(0.13 * radius) ball:setScale(0.13 * radius)
local body = cc.PhysicsBody:createCircle(ball:getContentSize().width / 2, material) local body = cc.PhysicsBody:createCircle(ball:getContentSize().width / 2, material)
-- ball:setPhysicsBody(body) ball:setPhysicsBody(body)
addPhysicsComponent(ball, body)
ball:setPosition(point) ball:setPosition(point)
return ball return ball
@ -146,7 +137,7 @@ local function makeBox(point, size, color, material)
box:setScaleY(size.height/100.0) box:setScaleY(size.height/100.0)
local body = cc.PhysicsBody:createBox(box:getContentSize(), material) local body = cc.PhysicsBody:createBox(box:getContentSize(), material)
addPhysicsComponent(box, body) box:setPhysicsBody(body)
box:setPosition(cc.p(point.x, point.y)) box:setPosition(cc.p(point.x, point.y))
return box return box
@ -176,7 +167,7 @@ local function makeTriangle(point, size, color, material)
} }
local body = cc.PhysicsBody:createPolygon(vers, material) local body = cc.PhysicsBody:createPolygon(vers, material)
addPhysicsComponent(triangle, body) triangle:setPhysicsBody(body)
triangle:setPosition(point) triangle:setPosition(point)
return triangle return triangle
@ -199,8 +190,7 @@ local function PhysicsDemoClickAdd()
addGrossiniAtPosition(layer, VisibleRect:center()) addGrossiniAtPosition(layer, VisibleRect:center())
local node = cc.Node:create() local node = cc.Node:create()
addPhysicsComponent(node, node:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
VisibleRect:getVisibleRect().height VisibleRect:getVisibleRect().height
) )
) )
@ -278,7 +268,7 @@ local function PhysicsDemoLogoSmash()
2*(logo_height-y + y_jitter) + VisibleRect:getVisibleRect().height/2 - logo_height/2), 2*(logo_height-y + y_jitter) + VisibleRect:getVisibleRect().height/2 - logo_height/2),
0.95, 0.95,
cc.PhysicsMaterial(0.01, 0.0, 0.0)) 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:setMass(1.0)
physicsBody:setMoment(PHYSICS_INFINITY) 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)) 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)) bullet:setPosition(cc.p(-500, VisibleRect:getVisibleRect().height/2))
layer.ball:addChild(bullet) layer.ball:addChild(bullet)
end end
@ -317,7 +307,7 @@ local function PhysicsDemoJoints()
local node = cc.Node:create() local node = cc.Node:create()
local box = cc.PhysicsBody:create() local box = cc.PhysicsBody:create()
addPhysicsComponent(node, box) node:setPhysicsBody(box)
box:setDynamic(false) box:setDynamic(false)
node:setPosition(cc.p(0, 0)) node:setPosition(cc.p(0, 0))
layer:addChild(node) layer:addChild(node)
@ -336,11 +326,11 @@ local function PhysicsDemoJoints()
if index == 0 then if index == 0 then
local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBall(layer, cc.p(offset.x + 30, offset.y), 10) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
local joint = cc.PhysicsJointPin:construct(sp1PhysicsBody, sp2PhysicsBody, offset) local joint = cc.PhysicsJointPin:construct(sp1PhysicsBody, sp2PhysicsBody, offset)
@ -350,11 +340,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 1 then elseif index == 1 then
local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
local joint = cc.PhysicsJointFixed:construct(sp1PhysicsBody, sp2PhysicsBody, offset) local joint = cc.PhysicsJointFixed:construct(sp1PhysicsBody, sp2PhysicsBody, offset)
@ -364,11 +354,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 2 then elseif index == 2 then
local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
local joint = cc.PhysicsJointDistance:construct(sp1PhysicsBody, local joint = cc.PhysicsJointDistance:construct(sp1PhysicsBody,
@ -381,11 +371,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 3 then elseif index == 3 then
local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
local joint = cc.PhysicsJointLimit:construct(sp1PhysicsBody, local joint = cc.PhysicsJointLimit:construct(sp1PhysicsBody,
@ -400,11 +390,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 4 then elseif index == 4 then
local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
local joint = cc.PhysicsJointSpring:construct(sp1PhysicsBody, local joint = cc.PhysicsJointSpring:construct(sp1PhysicsBody,
@ -419,11 +409,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 5 then elseif index == 5 then
local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
local joint = cc.PhysicsJointGroove:construct(sp1PhysicsBody, local joint = cc.PhysicsJointGroove:construct(sp1PhysicsBody,
@ -437,11 +427,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 6 then elseif index == 6 then
local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody,
@ -460,11 +450,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 7 then elseif index == 7 then
local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody,
@ -483,11 +473,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 8 then elseif index == 8 then
local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody,
@ -506,11 +496,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 9 then elseif index == 9 then
local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody,
@ -526,11 +516,11 @@ local function PhysicsDemoJoints()
layer:addChild(sp2) layer:addChild(sp2)
elseif index == 10 then elseif index == 10 then
local sp1 = makeBox(cc.p(offset.x - 30, offset.y), cc.size(30, 10)) 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) sp1PhysicsBody:setTag(DRAG_BODYS_TAG)
local sp2 = makeBox(cc.p(offset.x + 30, offset.y), cc.size(30, 10)) 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) sp2PhysicsBody:setTag(DRAG_BODYS_TAG)
scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody, scene:getPhysicsWorld():addJoint(cc.PhysicsJointPin:construct(sp1PhysicsBody,
@ -566,8 +556,7 @@ local function PhysicsDemoPyramidStack()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
local node = cc.Node:create() local node = cc.Node:create()
addPhysicsComponent(node, node:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
VisibleRect:leftBottom().y + 50), VisibleRect:leftBottom().y + 50),
cc.p(VisibleRect:rightBottom().x, cc.p(VisibleRect:rightBottom().x,
VisibleRect:rightBottom().y + 50))) VisibleRect:rightBottom().y + 50)))
@ -575,8 +564,8 @@ local function PhysicsDemoPyramidStack()
local ball = cc.Sprite:create("Images/ball.png") local ball = cc.Sprite:create("Images/ball.png")
ball:setScale(1) ball:setScale(1)
addPhysicsComponent(ball, cc.PhysicsBody:createCircle(10)) ball:setPhysicsBody(cc.PhysicsBody:createCircle(10))
ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) ball:getPhysicsBody():setTag(DRAG_BODYS_TAG)
ball:setPosition(cc.p(VisibleRect:bottom().x, VisibleRect:bottom().y + 60)) ball:setPosition(cc.p(VisibleRect:bottom().x, VisibleRect:bottom().y + 60))
layer:addChild(ball) layer:addChild(ball)
@ -588,7 +577,7 @@ local function PhysicsDemoPyramidStack()
local x = VisibleRect:bottom().x + (i/2 - j) * 11 local x = VisibleRect:bottom().x + (i/2 - j) * 11
local y = VisibleRect:bottom().y + (14 - i) * 23 + 100 local y = VisibleRect:bottom().y + (14 - i) * 23 + 100
local sp = addGrossiniAtPosition(layer, cc.p(x, y), 0.2) 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 end
end end
@ -625,8 +614,7 @@ local function PhysicsDemoRayCast()
cc.Director:getInstance():getRunningScene():getPhysicsWorld():setGravity(cc.p(0,0)) cc.Director:getInstance():getRunningScene():getPhysicsWorld():setGravity(cc.p(0,0))
local node = cc.DrawNode:create() local node = cc.DrawNode:create()
addPhysicsComponent(node, node:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
VisibleRect:leftBottom().y + 50), VisibleRect:leftBottom().y + 50),
cc.p(VisibleRect:rightBottom().x, cc.p(VisibleRect:rightBottom().x,
VisibleRect:rightBottom().y + 50))) VisibleRect:rightBottom().y + 50)))
@ -742,21 +730,20 @@ local function PhysicsDemoOneWayPlatform()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
local ground = cc.Node:create() local ground = cc.Node:create()
addPhysicsComponent(ground, ground:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
VisibleRect:leftBottom().y + 50), VisibleRect:leftBottom().y + 50),
cc.p(VisibleRect:rightBottom().x, cc.p(VisibleRect:rightBottom().x,
VisibleRect:rightBottom().y + 50))) VisibleRect:rightBottom().y + 50)))
layer:addChild(ground) layer:addChild(ground)
local platform = makeBox(VisibleRect:center(), cc.size(200, 50)) 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:setDynamic(false)
platformPhysicsBody:setContactTestBitmask(0xFFFFFFFF) platformPhysicsBody:setContactTestBitmask(0xFFFFFFFF)
layer:addChild(platform) layer:addChild(platform)
local ball = makeBall(layer, cc.p(VisibleRect:center().x, VisibleRect:center().y - 50), 20) 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:setVelocity(cc.p(0, 150))
ballPhysicsBody:setTag(DRAG_BODYS_TAG) ballPhysicsBody:setTag(DRAG_BODYS_TAG)
ballPhysicsBody:setMass(1.0) ballPhysicsBody:setMass(1.0)
@ -788,8 +775,7 @@ local function PhysicsDemoActions()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
local node = cc.Node:create() local node = cc.Node:create()
addPhysicsComponent(node, node:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
VisibleRect:getVisibleRect().height))) VisibleRect:getVisibleRect().height)))
node:setPosition(VisibleRect:center()) node:setPosition(VisibleRect:center())
layer:addChild(node) layer:addChild(node)
@ -798,7 +784,7 @@ local function PhysicsDemoActions()
local sp2 = addGrossiniAtPosition(layer, cc.p(VisibleRect:left().x + 50, VisibleRect:left().y)) 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 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)) 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) local actionTo = cc.JumpTo:create(2, cc.p(100,100), 50, 4)
@ -930,11 +916,11 @@ local function PhysicsDemoPump()
VisibleRect:leftTop().y), VisibleRect:leftTop().y),
22, 22,
cc.PhysicsMaterial(0.05, 0.0, 0.1)) 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) layer:addChild(ball)
end end
addPhysicsComponent(node, body) node:setPhysicsBody(body)
layer:addChild(node) layer:addChild(node)
local vec = local vec =
@ -950,7 +936,7 @@ local function PhysicsDemoPump()
-- small gear -- small gear
local sgear = cc.Node:create() local sgear = cc.Node:create()
local sgearB = cc.PhysicsBody:createCircle(44) local sgearB = cc.PhysicsBody:createCircle(44)
addPhysicsComponent(sgear, sgearB) sgear:setPhysicsBody(sgearB)
sgear:setPosition(cc.p(VisibleRect:leftBottom().x + 125, VisibleRect:leftBottom().y)) sgear:setPosition(cc.p(VisibleRect:leftBottom().x + 125, VisibleRect:leftBottom().y))
layer:addChild(sgear) layer:addChild(sgear)
sgearB:setCategoryBitmask(4) sgearB:setCategoryBitmask(4)
@ -962,7 +948,7 @@ local function PhysicsDemoPump()
-- big gear -- big gear
local bgear = cc.Node:create() local bgear = cc.Node:create()
local bgearB = cc.PhysicsBody:createCircle(100) local bgearB = cc.PhysicsBody:createCircle(100)
addPhysicsComponent(bgear, bgearB) bgear:setPhysicsBody(bgearB)
bgear:setPosition(cc.p(VisibleRect:leftBottom().x + 275, VisibleRect:leftBottom().y)) bgear:setPosition(cc.p(VisibleRect:leftBottom().x + 275, VisibleRect:leftBottom().y))
layer:addChild(bgear) layer:addChild(bgear)
bgearB:setCategoryBitmask(4) bgearB:setCategoryBitmask(4)
@ -976,7 +962,7 @@ local function PhysicsDemoPump()
local pumpB = cc.PhysicsBody:createPolygon(vec, local pumpB = cc.PhysicsBody:createPolygon(vec,
cc.PHYSICSBODY_MATERIAL_DEFAULT, cc.PHYSICSBODY_MATERIAL_DEFAULT,
cc.p(-center.x, -center.y)) cc.p(-center.x, -center.y))
addPhysicsComponent(pump, pumpB) pump:setPhysicsBody(pumpB)
layer:addChild(pump) layer:addChild(pump)
pumpB:setCategoryBitmask(2) pumpB:setCategoryBitmask(2)
pumpB:setGravityEnable(false) pumpB:setGravityEnable(false)
@ -996,7 +982,7 @@ local function PhysicsDemoPump()
pluggerB:setDynamic(true) pluggerB:setDynamic(true)
pluggerB:setMass(30) pluggerB:setMass(30)
pluggerB:setMoment(100000) pluggerB:setMoment(100000)
addPhysicsComponent(plugger, pluggerB) plugger:setPhysicsBody(pluggerB)
plugger:setPosition(segCenter) plugger:setPosition(segCenter)
layer:addChild(plugger) layer:addChild(plugger)
pluggerB:setCategoryBitmask(2) pluggerB:setCategoryBitmask(2)
@ -1054,7 +1040,7 @@ local function PhysicsDemoSlice()
cc.PHYSICSBODY_MATERIAL_DEFAULT, cc.PHYSICSBODY_MATERIAL_DEFAULT,
cc.p(-center.x, -center.y)) cc.p(-center.x, -center.y))
node:setPosition(center) node:setPosition(center)
addPhysicsComponent(node, polyon) node:setPhysicsBody(polyon)
polyon:setVelocity(body:getVelocityAtWorldPoint(center)) polyon:setVelocity(body:getVelocityAtWorldPoint(center))
polyon:setAngularVelocity(body:getAngularVelocity()) polyon:setAngularVelocity(body:getAngularVelocity())
polyon.tag = sliceTag polyon.tag = sliceTag
@ -1093,8 +1079,7 @@ local function PhysicsDemoSlice()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
local ground = cc.Node:create() local ground = cc.Node:create()
addPhysicsComponent(ground, ground:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x,
VisibleRect:leftBottom().y + 50), VisibleRect:leftBottom().y + 50),
cc.p(VisibleRect:rightBottom().x, cc.p(VisibleRect:rightBottom().x,
VisibleRect:rightBottom().y + 50))) VisibleRect:rightBottom().y + 50)))
@ -1102,9 +1087,9 @@ local function PhysicsDemoSlice()
local box = cc.Node:create() local box = cc.Node:create()
local points = {cc.p(-100, -100), cc.p(-100, 100), cc.p(100, 100), cc.p(100, -100)} 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:setPosition(VisibleRect:center())
box:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody().tag = sliceTag box:getPhysicsBody().tag = sliceTag
layer:addChild(box) layer:addChild(box)
end end
@ -1191,7 +1176,7 @@ local function PhysicsContactTest()
label:setPosition(cc.p(s.width/2, s.height-170)) label:setPosition(cc.p(s.width/2, s.height-170))
local wall = cc.Node:create() 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()) wall:setPosition(VisibleRect:center())
root:addChild(wall) root:addChild(wall)
@ -1207,7 +1192,7 @@ local function PhysicsContactTest()
VisibleRect:leftBottom().y + position.y + size.height/2) VisibleRect:leftBottom().y + position.y + size.height/2)
local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) 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 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:setVelocity(velocity)
boxPhysicsBody:setCategoryBitmask(1) -- 0001 boxPhysicsBody:setCategoryBitmask(1) -- 0001
boxPhysicsBody:setContactTestBitmask(4) -- 0100 boxPhysicsBody:setContactTestBitmask(4) -- 0100
@ -1226,7 +1211,7 @@ local function PhysicsContactTest()
VisibleRect:leftBottom().y + position.y + size.height/2) VisibleRect:leftBottom().y + position.y + size.height/2)
local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) 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 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:setVelocity(velocity)
boxPhysicsBody:setCategoryBitmask(2) -- 0010 boxPhysicsBody:setCategoryBitmask(2) -- 0010
boxPhysicsBody:setContactTestBitmask(8) -- 1000 boxPhysicsBody:setContactTestBitmask(8) -- 1000
@ -1246,7 +1231,7 @@ local function PhysicsContactTest()
VisibleRect:leftBottom().y + position.y + size.height/2) VisibleRect:leftBottom().y + position.y + size.height/2)
local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) 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 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:setVelocity(velocity)
trianglePhysicsBody:setCategoryBitmask(4) -- 0100 trianglePhysicsBody:setCategoryBitmask(4) -- 0100
trianglePhysicsBody:setContactTestBitmask(1) -- 0001 trianglePhysicsBody:setContactTestBitmask(1) -- 0001
@ -1266,7 +1251,7 @@ local function PhysicsContactTest()
VisibleRect:leftBottom().y + position.y + size.height/2) VisibleRect:leftBottom().y + position.y + size.height/2)
local velocity = cc.p((math.random() - 0.5)*200, (math.random() - 0.5)*200) 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 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:setVelocity(velocity)
trianglePhysicsBody:setCategoryBitmask(8) -- 1000 trianglePhysicsBody:setCategoryBitmask(8) -- 1000
trianglePhysicsBody:setContactTestBitmask(2) -- 0010 trianglePhysicsBody:setContactTestBitmask(2) -- 0010
@ -1410,8 +1395,7 @@ local function PhysicsPositionRotationTest()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
local wall = cc.Node:create() local wall = cc.Node:create()
addPhysicsComponent(wall, wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(VisibleRect:getVisibleRect()))
cc.PhysicsBody:createEdgeBox(VisibleRect:getVisibleRect()))
wall:setPosition(VisibleRect:center()) wall:setPosition(VisibleRect:center())
layer:addChild(wall) layer:addChild(wall)
@ -1420,9 +1404,8 @@ local function PhysicsPositionRotationTest()
anchorNode:setAnchorPoint(cc.p(0.1, 0.9)) anchorNode:setAnchorPoint(cc.p(0.1, 0.9))
anchorNode:setPosition(100, 100) anchorNode:setPosition(100, 100)
anchorNode:setScale(0.25) anchorNode:setScale(0.25)
addPhysicsComponent(anchorNode, anchorNode:setPhysicsBody(cc.PhysicsBody:createBox(anchorNode:getContentSize()))
cc.PhysicsBody:createBox(anchorNode:getContentSize())) anchorNode:getPhysicsBody():setTag(DRAG_BODYS_TAG)
anchorNode:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG)
layer:addChild(anchorNode) layer:addChild(anchorNode)
--parent test --parent test
@ -1430,15 +1413,15 @@ local function PhysicsPositionRotationTest()
parent:setPosition(200, 100) parent:setPosition(200, 100)
parent:setScale(0.25) parent:setScale(0.25)
local parentPhysicsBody = cc.PhysicsBody:createBox(anchorNode:getContentSize()) local parentPhysicsBody = cc.PhysicsBody:createBox(anchorNode:getContentSize())
addPhysicsComponent(parent, parentPhysicsBody) parent:setPhysicsBody(parentPhysicsBody)
parentPhysicsBody:setTag(DRAG_BODYS_TAG) parentPhysicsBody:setTag(DRAG_BODYS_TAG)
layer:addChild(parent) layer:addChild(parent)
local leftBall = cc.Sprite:create("Images/ball.png") local leftBall = cc.Sprite:create("Images/ball.png")
leftBall:setPosition(-30, 0) leftBall:setPosition(-30, 0)
leftBall:setScale(2) leftBall:setScale(2)
addPhysicsComponent(leftBall, cc.PhysicsBody:createCircle(leftBall:getContentSize().width / 2)) leftBall:setPhysicsBody(cc.PhysicsBody:createCircle(leftBall:getContentSize().width / 2))
leftBall:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) leftBall:getPhysicsBody():setTag(DRAG_BODYS_TAG)
parent:addChild(leftBall) parent:addChild(leftBall)
-- offset position rotation test -- offset position rotation test
@ -1446,7 +1429,7 @@ local function PhysicsPositionRotationTest()
offsetPosNode:setPosition(100, 200) offsetPosNode:setPosition(100, 200)
local offsetPosNodePhysicsBody = cc.PhysicsBody:createBox(cc.size(offsetPosNode:getContentSize().width/2, local offsetPosNodePhysicsBody = cc.PhysicsBody:createBox(cc.size(offsetPosNode:getContentSize().width/2,
offsetPosNode:getContentSize().height/2)) offsetPosNode:getContentSize().height/2))
addPhysicsComponent(offsetPosNode, offsetPosNodePhysicsBody) offsetPosNode:setPhysicsBody(offsetPosNodePhysicsBody)
offsetPosNodePhysicsBody:setPositionOffset(cc.p(-offsetPosNode:getContentSize().width/2, offsetPosNodePhysicsBody:setPositionOffset(cc.p(-offsetPosNode:getContentSize().width/2,
-offsetPosNode:getContentSize().height/2)) -offsetPosNode:getContentSize().height/2))
offsetPosNodePhysicsBody:setRotationOffset(45) offsetPosNodePhysicsBody:setRotationOffset(45)
@ -1472,19 +1455,18 @@ local function PhysicsSetGravityEnableTest()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
local wall = cc.Node:create() local wall = cc.Node:create()
addPhysicsComponent(wall, wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
VisibleRect:getVisibleRect().height), VisibleRect:getVisibleRect().height),
cc.PhysicsMaterial(0.1, 1.0, 0.0))) cc.PhysicsMaterial(0.1, 1.0, 0.0)))
wall:setPosition(VisibleRect:center()); wall:setPosition(VisibleRect:center());
layer:addChild(wall) layer:addChild(wall)
local commonBox = makeBox(cc.p(100, 100), cc.size(50, 50), 1) 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) layer:addChild(commonBox)
local box = makeBox(cc.p(200, 100), cc.size(50, 50), 2) 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:setMass(20)
boxBody:setTag(DRAG_BODYS_TAG) boxBody:setTag(DRAG_BODYS_TAG)
boxBody:setGravityEnable(false) boxBody:setGravityEnable(false)
@ -1492,7 +1474,7 @@ local function PhysicsSetGravityEnableTest()
local ball = makeBall(layer,cc.p(200,200),50) local ball = makeBall(layer,cc.p(200,200),50)
ball:setTag(2) ball:setTag(2)
local ballBody = ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody() local ballBody = ball:getPhysicsBody()
ballBody:setTag(DRAG_BODYS_TAG) ballBody:setTag(DRAG_BODYS_TAG)
ballBody:setGravityEnable(false) ballBody:setGravityEnable(false)
ballBody:setMass(50) ballBody:setMass(50)
@ -1501,7 +1483,7 @@ local function PhysicsSetGravityEnableTest()
local function onScheduleOnce() local function onScheduleOnce()
cclog("onScheduleOnce") cclog("onScheduleOnce")
local ball = layer:getChildByTag(2) 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)) cc.Director:getInstance():getRunningScene():getPhysicsWorld():setGravity(cc.p(0, 98))
end end
--layer:scheduleOnce(onScheduleOnce,1.0) --layer:scheduleOnce(onScheduleOnce,1.0)
@ -1531,8 +1513,7 @@ local function PhysicsDemoBug5482()
-- wall -- wall
local wall = cc.Node:create() local wall = cc.Node:create()
addPhysicsComponent(wall, wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
VisibleRect:getVisibleRect().height), VisibleRect:getVisibleRect().height),
cc.PhysicsMaterial(0.1, 1.0, 0.0))) cc.PhysicsMaterial(0.1, 1.0, 0.0)))
wall:setPosition(VisibleRect:center()); wall:setPosition(VisibleRect:center());
@ -1540,12 +1521,12 @@ local function PhysicsDemoBug5482()
local _nodeA = cc.Sprite:create("Images/YellowSquare.png") local _nodeA = cc.Sprite:create("Images/YellowSquare.png")
_nodeA:setPosition(cc.p(VisibleRect:center().x-150,100)) _nodeA:setPosition(cc.p(VisibleRect:center().x-150,100))
addPhysicsComponent(_nodeA,nil) _nodeA:setPhysicsBody(nil)
layer:addChild(_nodeA) layer:addChild(_nodeA)
local _nodeB = cc.Sprite:create("Images/YellowSquare.png") local _nodeB = cc.Sprite:create("Images/YellowSquare.png")
_nodeB:setPosition(cc.p(VisibleRect:center().x+150,100)) _nodeB:setPosition(cc.p(VisibleRect:center().x+150,100))
addPhysicsComponent(_nodeB,nil) _nodeB:setPhysicsBody(nil)
layer:addChild(_nodeB) layer:addChild(_nodeB)
local _body = cc.PhysicsBody:createBox(_nodeA:getContentSize()) local _body = cc.PhysicsBody:createBox(_nodeA:getContentSize())
@ -1561,7 +1542,7 @@ local function PhysicsDemoBug5482()
node = _nodeA node = _nodeA
cclog("_nodeA") cclog("_nodeA")
end end
node:getComponent(PHYSICS_COMPONENT_NAME):setPhysicsBody(_body) node:setPhysicsBody(_body)
_bodyInA = not _bodyInA _bodyInA = not _bodyInA
end end
@ -1588,9 +1569,9 @@ local function PhysicsDemoBug5482()
local function addBall() local function addBall()
local ball = cc.Sprite:create("Images/ball.png") local ball = cc.Sprite:create("Images/ball.png")
ball:setPosition(cc.p(100,100)) ball:setPosition(cc.p(100,100))
addPhysicsComponent(ball,cc.PhysicsBody:createCircle(ball:getContentSize().width/2, cc.PhysicsMaterial(0.1, 1, 0.0))) ball:setPhysicsBody(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:getPhysicsBody():setTag(DRAG_BODYS_TAG)
ball:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setVelocity(cc.p(1000,20)) ball:getPhysicsBody():setVelocity(cc.p(1000,20))
layer:addChild(ball) layer:addChild(ball)
end end
@ -1608,8 +1589,7 @@ local function PhysicsDemoBug5482()
-- wall -- wall
local wall = cc.Node:create() local wall = cc.Node:create()
addPhysicsComponent(wall, wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
VisibleRect:getVisibleRect().height), VisibleRect:getVisibleRect().height),
cc.PhysicsMaterial(0.1, 1.0, 0.0))) cc.PhysicsMaterial(0.1, 1.0, 0.0)))
wall:setPosition(VisibleRect:center()); wall:setPosition(VisibleRect:center());
@ -1642,8 +1622,7 @@ local function PhysicsTransformTest()
layer:addChild(_rootLayer) layer:addChild(_rootLayer)
local wall = cc.Node:create() local wall = cc.Node:create()
addPhysicsComponent(wall, wall:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width,
VisibleRect:getVisibleRect().height), VisibleRect:getVisibleRect().height),
cc.PhysicsMaterial(0.1, 1.0, 0.0))) cc.PhysicsMaterial(0.1, 1.0, 0.0)))
wall:setPosition(VisibleRect:center()); wall:setPosition(VisibleRect:center());
@ -1652,16 +1631,16 @@ local function PhysicsTransformTest()
local _parentSprite = cc.Sprite:create("Images/YellowSquare.png") local _parentSprite = cc.Sprite:create("Images/YellowSquare.png")
_parentSprite:setPosition(cc.p(200,100)) _parentSprite:setPosition(cc.p(200,100))
_parentSprite:setScale(0.25) _parentSprite:setScale(0.25)
addPhysicsComponent(_parentSprite,cc.PhysicsBody:createBox(_parentSprite:getContentSize(),cc.PhysicsMaterial(0.1, 1.0, 0.0))) _parentSprite:setPhysicsBody(cc.PhysicsBody:createBox(_parentSprite:getContentSize(),cc.PhysicsMaterial(0.1, 1.0, 0.0)))
_parentSprite:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) _parentSprite:getPhysicsBody():setTag(DRAG_BODYS_TAG)
_parentSprite:setTag(1) _parentSprite:setTag(1)
_rootLayer:addChild(_parentSprite) _rootLayer:addChild(_parentSprite)
local leftBall = cc.Sprite:create("Images/ball.png") local leftBall = cc.Sprite:create("Images/ball.png")
leftBall:setPosition(cc.p(-30,0)) leftBall:setPosition(cc.p(-30,0))
leftBall:setScale(2) leftBall:setScale(2)
addPhysicsComponent(leftBall,cc.PhysicsBody:createCircle(leftBall:getContentSize().width/2,cc.PhysicsMaterial(0.1,1.0,0.0))) leftBall:setPhysicsBody(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:getPhysicsBody():setTag(DRAG_BODYS_TAG)
_parentSprite:addChild(leftBall) _parentSprite:addChild(leftBall)
local scaleTo = cc.ScaleTo:create(2.0,0.5) local scaleTo = cc.ScaleTo:create(2.0,0.5)
@ -1671,14 +1650,14 @@ local function PhysicsTransformTest()
local normal = cc.Sprite:create("Images/YellowSquare.png") local normal = cc.Sprite:create("Images/YellowSquare.png")
normal:setPosition(cc.p(300,100)) normal:setPosition(cc.p(300,100))
normal:setScale(0.25,0.5) normal:setScale(0.25,0.5)
addPhysicsComponent(normal,cc.PhysicsBody:createBox(normal:getContentSize()),cc.PhysicsMaterial(0.1,1.0,0.0)) normal:setPhysicsBody(cc.PhysicsBody:createBox(normal:getContentSize()),cc.PhysicsMaterial(0.1,1.0,0.0))
normal:getComponent(PHYSICS_COMPONENT_NAME):getPhysicsBody():setTag(DRAG_BODYS_TAG) normal:getPhysicsBody():setTag(DRAG_BODYS_TAG)
_rootLayer:addChild(normal) _rootLayer:addChild(normal)
local bullet = cc.Sprite:create("Images/ball.png") local bullet = cc.Sprite:create("Images/ball.png")
bullet:setPosition(cc.p(200,200)) bullet:setPosition(cc.p(200,200))
addPhysicsComponent(bullet,cc.PhysicsBody:createCircle(bullet:getContentSize().width/2,cc.PhysicsMaterial(0.1,1.0,0.0))) bullet:setPhysicsBody(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:getPhysicsBody():setVelocity(cc.p(100,100))
_rootLayer:addChild(bullet) _rootLayer:addChild(bullet)
local move = cc.MoveBy:create(2.0,cc.p(100,100)) local move = cc.MoveBy:create(2.0,cc.p(100,100))

View File

@ -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 # will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes. # 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], Sprite::[getQuad ^setPosition$ ^create$ setPolygonInfo initWithPolygon getPolygonInfo],
SpriteBatchNode::[getDescendants], SpriteBatchNode::[getDescendants],
MotionStreak::[draw update], MotionStreak::[draw update],

View File

@ -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 # 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*$". # 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] # 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 # 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$], PhysicsShapeEdgePolygon::[create ^getPoints$],
PhysicsShapeEdgeChain::[create ^getPoints$], PhysicsShapeEdgeChain::[create ^getPoints$],
PhysicsWorld::[getScene queryPoint queryRect rayCast], PhysicsWorld::[getScene queryPoint queryRect rayCast],
PhysicsContact::[getData setData], PhysicsContact::[getData setData]
PhysicsManager::[PhysicsManager update],
ComponentPhysics2d::[beforeSimulation afterSimulation]
rename_functions = rename_functions =