CCPhysicsBody.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /****************************************************************************
  2. Copyright (c) 2013-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #ifndef __CCPHYSICS_BODY_H__
  22. #define __CCPHYSICS_BODY_H__
  23. #include "base/ccConfig.h"
  24. #if CC_USE_PHYSICS
  25. #include "2d/CCComponent.h"
  26. #include "math/CCGeometry.h"
  27. #include "physics/CCPhysicsShape.h"
  28. #include "base/CCVector.h"
  29. struct cpBody;
  30. NS_CC_BEGIN
  31. class Node;
  32. class PhysicsWorld;
  33. class PhysicsJoint;
  34. typedef Vec2 Vect;
  35. const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f);
  36. /**
  37. * @addtogroup physics
  38. * @{
  39. * @addtogroup physics_2d
  40. * @{
  41. */
  42. /**
  43. * A body affect by physics.
  44. *
  45. * It can attach one or more shapes.
  46. * If you create body with createXXX, it will automatically compute mass and moment with density your specified(which is PHYSICSBODY_MATERIAL_DEFAULT by default, and the density value is 0.1f), and it based on the formula: mass = density * area.
  47. * If you create body with createEdgeXXX, the mass and moment will be PHYSICS_INFINITY by default. And it's a static body.
  48. * 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().
  49. */
  50. class CC_DLL PhysicsBody : public Component
  51. {
  52. public:
  53. const static std::string COMPONENT_NAME;
  54. /**
  55. * Create a body with default mass and moment.
  56. *
  57. * This default mass value is 1.0.
  58. * This default moment value is 200.
  59. * @return An autoreleased PhysicsBody object pointer.
  60. */
  61. static PhysicsBody* create();
  62. /**
  63. * Create a body with mass and default moment.
  64. *
  65. * @param mass This body's mass.
  66. * @return An autoreleased PhysicsBody object pointer.
  67. */
  68. static PhysicsBody* create(float mass);
  69. /**
  70. * Create a body with mass and moment.
  71. *
  72. * @param mass This body's mass.
  73. * @param moment This body's moment.
  74. * @return An autoreleased PhysicsBody object pointer.
  75. */
  76. static PhysicsBody* create(float mass, float moment);
  77. /**
  78. * Create a body contains a circle.
  79. *
  80. * @param radius A float number, it is the circle's radius.
  81. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
  82. * @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.
  83. * @return An autoreleased PhysicsBody object pointer.
  84. */
  85. static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
  86. /**
  87. * Create a body contains a box shape.
  88. *
  89. * @param size Size contains this box's width and height.
  90. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
  91. * @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.
  92. * @return An autoreleased PhysicsBody object pointer.
  93. */
  94. static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
  95. /**
  96. * @brief Create a body contains a polygon shape.
  97. *
  98. * @param points Points is an array of Vec2 structs defining a convex hull with a clockwise winding.
  99. * @param count An integer number, contains the count of the points array.
  100. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
  101. * @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.
  102. * @return An autoreleased PhysicsBody object pointer.
  103. */
  104. static PhysicsBody* createPolygon(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
  105. /**
  106. * Create a body contains a EdgeSegment shape.
  107. *
  108. * @param a It's the edge's begin position.
  109. * @param b It's the edge's end position.
  110. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
  111. * @param border It's a edge's border width.
  112. * @return An autoreleased PhysicsBody object pointer.
  113. */
  114. static PhysicsBody* createEdgeSegment(const Vec2& a, const Vec2& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
  115. /**
  116. * Create a body contains a EdgeBox shape.
  117. * @param size Size contains this box's width and height.
  118. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
  119. * @param border It's a edge's border width.
  120. * @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.
  121. * @return An autoreleased PhysicsBody object pointer.
  122. */
  123. static PhysicsBody* createEdgeBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, const Vec2& offset = Vec2::ZERO);
  124. /**
  125. * Create a body contains a EdgePolygon shape.
  126. *
  127. * @param points Points is an array of Vec2 structs defining a convex hull with a clockwise winding.
  128. * @param count An integer number, contains the count of the points array.
  129. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
  130. * @param border It's a edge's border width.
  131. * @return An autoreleased PhysicsBody object pointer.
  132. */
  133. static PhysicsBody* createEdgePolygon(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
  134. /**
  135. * Create a body contains a EdgeChain shape.
  136. *
  137. * @param points A Vec2 object pointer, it contains an array of points.
  138. * @param count An integer number, contains the count of the points array.
  139. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
  140. * @param border It's a edge's border width.
  141. * @return An autoreleased PhysicsBody object pointer.
  142. */
  143. static PhysicsBody* createEdgeChain(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
  144. /**
  145. * @brief Add a shape to body.
  146. * @param shape The shape to be added.
  147. * @param addMassAndMoment If this is true, the shape's mass and moment will be added to body. The default is true.
  148. * @return This shape's pointer if added success or nullptr if failed.
  149. */
  150. virtual PhysicsShape* addShape(PhysicsShape* shape, bool addMassAndMoment = true);
  151. /**
  152. * @brief Remove a shape from body.
  153. * @param shape Shape the shape to be removed.
  154. * @param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true.
  155. */
  156. void removeShape(PhysicsShape* shape, bool reduceMassAndMoment = true);
  157. /**
  158. * @brief Remove a shape from body.
  159. * @param tag The tag of the shape to be removed.
  160. * @param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true.
  161. */
  162. void removeShape(int tag, bool reduceMassAndMoment = true);
  163. /**
  164. * Remove all shapes.
  165. *
  166. * @param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true.
  167. */
  168. void removeAllShapes(bool reduceMassAndMoment = true);
  169. /**
  170. * Get the body shapes.
  171. *
  172. * @return A Vector<PhysicsShape*> object contains PhysicsShape pointer.
  173. */
  174. const Vector<PhysicsShape*>& getShapes() const { return _shapes; }
  175. /**
  176. * Get the first shape of the body shapes.
  177. *
  178. * @return The first shape in this body.
  179. */
  180. PhysicsShape* getFirstShape() const { return _shapes.size() >= 1 ? _shapes.at(0) : nullptr; }
  181. /**
  182. * get the shape of the body.
  183. *
  184. * @param tag An integer number that identifies a PhysicsShape object.
  185. * @return A PhysicsShape object pointer or nullptr if no shapes were found.
  186. */
  187. PhysicsShape* getShape(int tag) const;
  188. /**
  189. * Applies a continuous force to body.
  190. *
  191. * @param force The force is applies to this body.
  192. * @param offset A Vec2 object, it is the offset from the body's center of gravity in world coordinates.
  193. */
  194. virtual void applyForce(const Vec2& force, const Vec2& offset = Vec2::ZERO);
  195. /**
  196. * reset all the force applied to body.
  197. */
  198. virtual void resetForces();
  199. /**
  200. * Applies a immediate force to body.
  201. *
  202. * @param impulse The impulse is applies to this body.
  203. * @param offset A Vec2 object, it is the offset from the body's center of gravity in world coordinates.
  204. */
  205. virtual void applyImpulse(const Vec2& impulse, const Vec2& offset = Vec2::ZERO);
  206. /**
  207. * Applies a torque force to body.
  208. *
  209. * @param torque The torque is applies to this body.
  210. */
  211. virtual void applyTorque(float torque);
  212. /**
  213. * Set the velocity of a body.
  214. *
  215. * @param velocity The velocity is set to this body.
  216. */
  217. virtual void setVelocity(const Vec2& velocity);
  218. /** Get the velocity of a body. */
  219. virtual Vec2 getVelocity();
  220. /**
  221. * Set the angular velocity of a body.
  222. *
  223. * @param velocity The angular velocity is set to this body.
  224. */
  225. virtual void setAngularVelocity(float velocity);
  226. /** Get the angular velocity of a body at a local point.*/
  227. virtual Vec2 getVelocityAtLocalPoint(const Vec2& point);
  228. /** get the angular velocity of a body at a world point */
  229. virtual Vec2 getVelocityAtWorldPoint(const Vec2& point);
  230. /** get the angular velocity of a body */
  231. virtual float getAngularVelocity();
  232. /** set the max of velocity */
  233. virtual void setVelocityLimit(float limit);
  234. /** get the max of velocity */
  235. virtual float getVelocityLimit();
  236. /** set the max of angular velocity */
  237. virtual void setAngularVelocityLimit(float limit);
  238. /** get the max of angular velocity */
  239. virtual float getAngularVelocityLimit();
  240. /** remove the body from the world it added to */
  241. void removeFromWorld();
  242. /** get the world body added to. */
  243. PhysicsWorld* getWorld() const { return _world; }
  244. /** get all joints the body have */
  245. const std::vector<PhysicsJoint*>& getJoints() const { return _joints; }
  246. /** get the node the body set to. */
  247. Node* getNode() const { return _owner; }
  248. /**
  249. * A mask that defines which categories this physics body belongs to.
  250. *
  251. * Every physics body in a scene can be assigned to up to 32 different categories, each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties, you define which physics bodies interact with each other and when your game is notified of these interactions.
  252. * @param bitmask An integer number, the default value is 0xFFFFFFFF (all bits set).
  253. */
  254. void setCategoryBitmask(int bitmask);
  255. /**
  256. * A mask that defines which categories of bodies cause intersection notifications with this physics body.
  257. *
  258. * When two bodies share the same space, each body's category mask is tested against the other body's contact mask by performing a logical AND operation. If either comparison results in a non-zero value, an PhysicsContact object is created and passed to the physics world’s delegate. For best performance, only set bits in the contacts mask for interactions you are interested in.
  259. * @param bitmask An integer number, the default value is 0x00000000 (all bits cleared).
  260. */
  261. void setContactTestBitmask(int bitmask);
  262. /**
  263. * A mask that defines which categories of physics bodies can collide with this physics body.
  264. *
  265. * When two physics bodies contact each other, a collision may occur. This body's collision mask is compared to the other body's category mask by performing a logical AND operation. If the result is a non-zero value, then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example, you might use this to avoid collision calculations that would make negligible changes to a body's velocity.
  266. * @param bitmask An integer number, the default value is 0xFFFFFFFF (all bits set).
  267. */
  268. void setCollisionBitmask(int bitmask);
  269. /**
  270. * Return bitmask of first shape.
  271. *
  272. * @return If there is no shape in body, return default value.(0xFFFFFFFF)
  273. */
  274. int getCategoryBitmask() const;
  275. /**
  276. * Return bitmask of first shape.
  277. *
  278. * @return If there is no shape in body, return default value.(0x00000000)
  279. */
  280. int getContactTestBitmask() const;
  281. /**
  282. * Return bitmask of first shape.
  283. *
  284. * @return If there is no shape in body, return default value.(0xFFFFFFFF)
  285. */
  286. int getCollisionBitmask() const;
  287. /**
  288. * Set the group of body.
  289. *
  290. * Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index).
  291. * It have high priority than bit masks.
  292. */
  293. void setGroup(int group);
  294. /**
  295. * Return group of first shape.
  296. *
  297. * @return If there is no shape in body, return default value.(0)
  298. */
  299. int getGroup() const;
  300. /** get the body position. */
  301. Vec2 getPosition() const;
  302. /** get the body rotation. */
  303. float getRotation();
  304. /** set body position offset, it's the position witch relative to node */
  305. void setPositionOffset(const Vec2& position);
  306. /** get body position offset. */
  307. const Vec2& getPositionOffset() const { return _positionOffset; }
  308. /** set body rotation offset, it's the rotation witch relative to node */
  309. void setRotationOffset(float rotation);
  310. /** set the body rotation offset */
  311. float getRotationOffset() const { return _rotationOffset; }
  312. /**
  313. * @brief Test the body is dynamic or not.
  314. *
  315. * A dynamic body will effect with gravity.
  316. */
  317. bool isDynamic() const { return _dynamic; }
  318. /**
  319. * @brief Set dynamic to body.
  320. *
  321. * A dynamic body will effect with gravity.
  322. */
  323. void setDynamic(bool dynamic);
  324. /**
  325. * @brief Set the body mass.
  326. *
  327. * @attention If you need add/subtract mass to body, don't use setMass(getMass() +/- mass), because the mass of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMass() instead.
  328. */
  329. void setMass(float mass);
  330. /** Get the body mass. */
  331. float getMass() const { return _mass; }
  332. /**
  333. * @brief Add mass to body.
  334. *
  335. * @param mass If _mass(mass of the body) == PHYSICS_INFINITY, it remains.
  336. * if mass == PHYSICS_INFINITY, _mass will be PHYSICS_INFINITY.
  337. * if mass == -PHYSICS_INFINITY, _mass will not change.
  338. * if mass + _mass <= 0, _mass will equal to MASS_DEFAULT(1.0)
  339. * other wise, mass = mass + _mass;
  340. */
  341. void addMass(float mass);
  342. /**
  343. * @brief Set the body moment of inertia.
  344. *
  345. * @note If you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead.
  346. */
  347. void setMoment(float moment);
  348. /** Get the body moment of inertia. */
  349. float getMoment() const { return _moment; }
  350. /**
  351. * @brief Add moment of inertia to body.
  352. *
  353. * @param moment If _moment(moment of the body) == PHYSICS_INFINITY, it remains.
  354. * if moment == PHYSICS_INFINITY, _moment will be PHYSICS_INFINITY.
  355. * if moment == -PHYSICS_INFINITY, _moment will not change.
  356. * if moment + _moment <= 0, _moment will equal to MASS_DEFAULT(1.0)
  357. * other wise, moment = moment + _moment;
  358. */
  359. void addMoment(float moment);
  360. /** get linear damping. */
  361. float getLinearDamping() const { return _linearDamping; }
  362. /**
  363. * Set linear damping.
  364. *
  365. * it is used to simulate fluid or air friction forces on the body.
  366. * @param damping The value is 0.0f to 1.0f.
  367. */
  368. void setLinearDamping(float damping) { _linearDamping = damping; updateDamping(); }
  369. /** Get angular damping. */
  370. float getAngularDamping() const { return _angularDamping; }
  371. /**
  372. * Set angular damping.
  373. *
  374. * It is used to simulate fluid or air friction forces on the body.
  375. * @param damping The value is 0.0f to 1.0f.
  376. */
  377. void setAngularDamping(float damping) { _angularDamping = damping; updateDamping(); }
  378. /** Whether the body is at rest. */
  379. bool isResting() const;
  380. /** set body to rest */
  381. void setResting(bool rest) const;
  382. /**
  383. * Set the enable value.
  384. *
  385. * If the body it isn't enabled, it will not has simulation by world.
  386. */
  387. virtual void setEnabled(bool enable) override;
  388. /** Whether the body can rotation. */
  389. bool isRotationEnabled() const { return _rotationEnabled; }
  390. /** Set the body is allow rotation or not */
  391. void setRotationEnable(bool enable);
  392. /** Whether this physics body is affected by the physics world's gravitational force. */
  393. bool isGravityEnabled() const { return _gravityEnabled; }
  394. /** Set the body is affected by the physics world's gravitational force or not. */
  395. void setGravityEnable(bool enable);
  396. /** Get the body's tag. */
  397. int getTag() const { return _tag; }
  398. /** set the body's tag. */
  399. void setTag(int tag) { _tag = tag; }
  400. /** Convert the world point to local. */
  401. Vec2 world2Local(const Vec2& point);
  402. /** Convert the local point to world. */
  403. Vec2 local2World(const Vec2& point);
  404. /** Get the rigid body of chipmunk. */
  405. cpBody* getCPBody() const { return _cpBody; }
  406. virtual void onEnter() override;
  407. virtual void onExit() override;
  408. virtual void onAdd() override;
  409. virtual void onRemove() override;
  410. protected:
  411. PhysicsBody();
  412. virtual ~PhysicsBody();
  413. virtual bool init()override;
  414. virtual void setPosition(float positionX, float positionY);
  415. virtual void setRotation(float rotation);
  416. virtual void setScale(float scaleX, float scaleY);
  417. void update(float delta)override;
  418. void removeJoint(PhysicsJoint* joint);
  419. void updateDamping() { _isDamping = _linearDamping != 0.0f || _angularDamping != 0.0f; }
  420. void addToPhysicsWorld();
  421. void removeFromPhysicsWorld();
  422. void beforeSimulation(const Mat4& parentToWorldTransform, const Mat4& nodeToWorldTransform, float scaleX, float scaleY, float rotation);
  423. void afterSimulation(const Mat4& parentToWorldTransform, float parentRotation);
  424. protected:
  425. std::vector<PhysicsJoint*> _joints;
  426. Vector<PhysicsShape*> _shapes;
  427. PhysicsWorld* _world;
  428. cpBody* _cpBody;
  429. bool _dynamic;
  430. bool _rotationEnabled;
  431. bool _gravityEnabled;
  432. bool _massDefault;
  433. bool _momentDefault;
  434. float _mass;
  435. float _area;
  436. float _density;
  437. float _moment;
  438. float _velocityLimit;
  439. float _angularVelocityLimit;
  440. bool _isDamping;
  441. float _linearDamping;
  442. float _angularDamping;
  443. int _tag;
  444. // when setMass() is invoked, it means body's mass is not calculated by shapes
  445. bool _massSetByUser;
  446. // when setMoment() is invoked, it means body's moment is not calculated by shapes
  447. bool _momentSetByUser;
  448. Vec2 _positionOffset;
  449. float _rotationOffset;
  450. float _recordedRotation;
  451. double _recordedAngle;
  452. // offset between owner's center point and down left point
  453. Vec3 _ownerCenterOffset;
  454. // offset of owner's center point and anchor point in parent coordinate
  455. Vec2 _offset;
  456. float _recordScaleX;
  457. float _recordScaleY;
  458. float _recordPosX;
  459. float _recordPosY;
  460. friend class PhysicsWorld;
  461. friend class PhysicsShape;
  462. friend class PhysicsJoint;
  463. };
  464. /** @} */
  465. /** @} */
  466. NS_CC_END
  467. #endif // CC_USE_PHYSICS
  468. #endif // __CCPHYSICS_BODY_H__