1
0

CCPhysicsBody.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /****************************************************************************
  2. Copyright (c) 2013-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #include "physics/CCPhysicsBody.h"
  21. #if CC_USE_PHYSICS
  22. #include <climits>
  23. #include <algorithm>
  24. #include <cmath>
  25. #include "chipmunk/chipmunk_private.h"
  26. #include "2d/CCScene.h"
  27. #include "physics/CCPhysicsShape.h"
  28. #include "physics/CCPhysicsJoint.h"
  29. #include "physics/CCPhysicsWorld.h"
  30. #include "physics/CCPhysicsHelper.h"
  31. static void internalBodySetMass(cpBody *body, cpFloat mass)
  32. {
  33. cpBodyActivate(body);
  34. body->m = mass;
  35. body->m_inv = 1.0f/mass;
  36. //cpAssertSaneBody(body);
  37. }
  38. static void internalBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
  39. {
  40. cpBodyUpdateVelocity(body, cpvzero, damping, dt);
  41. // Skip kinematic bodies.
  42. if(cpBodyGetType(body) == CP_BODY_TYPE_KINEMATIC) return;
  43. cpAssertSoft(body->m > 0.0f && body->i > 0.0f, "Body's mass and moment must be positive to simulate. (Mass: %f Moment: f)", body->m, body->i);
  44. cocos2d::PhysicsBody *physicsBody = static_cast<cocos2d::PhysicsBody*>(body->userData);
  45. if(physicsBody->isGravityEnabled())
  46. body->v = cpvclamp(cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt)), physicsBody->getVelocityLimit());
  47. else
  48. body->v = cpvclamp(cpvadd(cpvmult(body->v, damping), cpvmult(cpvmult(body->f, body->m_inv), dt)), physicsBody->getVelocityLimit());
  49. cpFloat w_limit = physicsBody->getAngularVelocityLimit();
  50. body->w = cpfclamp(body->w*damping + body->t*body->i_inv*dt, -w_limit, w_limit);
  51. // Reset forces.
  52. body->f = cpvzero;
  53. //to check body sanity
  54. cpBodySetTorque(body, 0.0f);
  55. }
  56. NS_CC_BEGIN
  57. extern const float PHYSICS_INFINITY;
  58. const std::string PhysicsBody::COMPONENT_NAME = "PhysicsBody";
  59. namespace
  60. {
  61. static const float MASS_DEFAULT = 1.0;
  62. static const float MOMENT_DEFAULT = 200;
  63. }
  64. PhysicsBody::PhysicsBody()
  65. : _world(nullptr)
  66. , _cpBody(nullptr)
  67. , _dynamic(true)
  68. , _rotationEnabled(true)
  69. , _gravityEnabled(true)
  70. , _massDefault(true)
  71. , _momentDefault(true)
  72. , _mass(MASS_DEFAULT)
  73. , _area(0.0f)
  74. , _density(0.0f)
  75. , _moment(MOMENT_DEFAULT)
  76. , _velocityLimit(PHYSICS_INFINITY)
  77. , _angularVelocityLimit(PHYSICS_INFINITY)
  78. , _isDamping(false)
  79. , _linearDamping(0.0f)
  80. , _angularDamping(0.0f)
  81. , _tag(0)
  82. , _rotationOffset(0)
  83. , _recordedRotation(0.0f)
  84. , _recordedAngle(0.0)
  85. , _massSetByUser(false)
  86. , _momentSetByUser(false)
  87. , _recordScaleX(1.f)
  88. , _recordScaleY(1.f)
  89. {
  90. _name = COMPONENT_NAME;
  91. }
  92. PhysicsBody::~PhysicsBody()
  93. {
  94. for (auto& joint : _joints)
  95. {
  96. PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA();
  97. other->removeJoint(joint);
  98. delete joint;
  99. }
  100. if (_cpBody)
  101. {
  102. cpBodyFree(_cpBody);
  103. }
  104. }
  105. PhysicsBody* PhysicsBody::create()
  106. {
  107. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  108. if (body && body->init())
  109. {
  110. body->autorelease();
  111. return body;
  112. }
  113. CC_SAFE_DELETE(body);
  114. return nullptr;
  115. }
  116. PhysicsBody* PhysicsBody::create(float mass)
  117. {
  118. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  119. if (body)
  120. {
  121. body->_mass = mass;
  122. body->_massDefault = false;
  123. if (body->init())
  124. {
  125. body->autorelease();
  126. return body;
  127. }
  128. }
  129. CC_SAFE_DELETE(body);
  130. return nullptr;
  131. }
  132. PhysicsBody* PhysicsBody::create(float mass, float moment)
  133. {
  134. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  135. if (body)
  136. {
  137. body->_mass = mass;
  138. body->_massDefault = false;
  139. body->_moment = moment;
  140. body->_momentDefault = false;
  141. if (body->init())
  142. {
  143. body->autorelease();
  144. return body;
  145. }
  146. }
  147. CC_SAFE_DELETE(body);
  148. return nullptr;
  149. }
  150. PhysicsBody* PhysicsBody::createCircle(float radius, const PhysicsMaterial& material, const Vec2& offset)
  151. {
  152. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  153. if (body && body->init())
  154. {
  155. body->addShape(PhysicsShapeCircle::create(radius, material, offset));
  156. body->autorelease();
  157. return body;
  158. }
  159. CC_SAFE_DELETE(body);
  160. return nullptr;
  161. }
  162. PhysicsBody* PhysicsBody::createBox(const Size& size, const PhysicsMaterial& material, const Vec2& offset)
  163. {
  164. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  165. if (body && body->init())
  166. {
  167. body->addShape(PhysicsShapeBox::create(size, material, offset));
  168. body->autorelease();
  169. return body;
  170. }
  171. CC_SAFE_DELETE(body);
  172. return nullptr;
  173. }
  174. PhysicsBody* PhysicsBody::createPolygon(const Vec2* points, int count, const PhysicsMaterial& material, const Vec2& offset)
  175. {
  176. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  177. if (body && body->init())
  178. {
  179. body->addShape(PhysicsShapePolygon::create(points, count, material, offset));
  180. body->autorelease();
  181. return body;
  182. }
  183. CC_SAFE_DELETE(body);
  184. return nullptr;
  185. }
  186. PhysicsBody* PhysicsBody::createEdgeSegment(const Vec2& a, const Vec2& b, const PhysicsMaterial& material, float border/* = 1*/)
  187. {
  188. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  189. if (body && body->init())
  190. {
  191. body->addShape(PhysicsShapeEdgeSegment::create(a, b, material, border));
  192. body->setDynamic(false);
  193. body->autorelease();
  194. return body;
  195. }
  196. CC_SAFE_DELETE(body);
  197. return nullptr;
  198. }
  199. PhysicsBody* PhysicsBody::createEdgeBox(const Size& size, const PhysicsMaterial& material, float border/* = 1*/, const Vec2& offset)
  200. {
  201. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  202. if (body && body->init())
  203. {
  204. body->addShape(PhysicsShapeEdgeBox::create(size, material, border, offset));
  205. body->setDynamic(false);
  206. body->autorelease();
  207. return body;
  208. }
  209. CC_SAFE_DELETE(body);
  210. return nullptr;
  211. }
  212. PhysicsBody* PhysicsBody::createEdgePolygon(const Vec2* points, int count, const PhysicsMaterial& material, float border/* = 1*/)
  213. {
  214. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  215. if (body && body->init())
  216. {
  217. body->addShape(PhysicsShapeEdgePolygon::create(points, count, material, border));
  218. body->setDynamic(false);
  219. body->autorelease();
  220. return body;
  221. }
  222. CC_SAFE_DELETE(body);
  223. return nullptr;
  224. }
  225. PhysicsBody* PhysicsBody::createEdgeChain(const Vec2* points, int count, const PhysicsMaterial& material, float border/* = 1*/)
  226. {
  227. PhysicsBody* body = new (std::nothrow) PhysicsBody();
  228. if (body && body->init())
  229. {
  230. body->addShape(PhysicsShapeEdgeChain::create(points, count, material, border));
  231. body->setDynamic(false);
  232. body->autorelease();
  233. return body;
  234. }
  235. CC_SAFE_DELETE(body);
  236. return nullptr;
  237. }
  238. bool PhysicsBody::init()
  239. {
  240. do
  241. {
  242. _cpBody = cpBodyNew(_mass, _moment);
  243. internalBodySetMass(_cpBody, _mass);
  244. cpBodySetUserData(_cpBody, this);
  245. cpBodySetVelocityUpdateFunc(_cpBody, internalBodyUpdateVelocity);
  246. CC_BREAK_IF(_cpBody == nullptr);
  247. return true;
  248. } while (false);
  249. return false;
  250. }
  251. void PhysicsBody::removeJoint(PhysicsJoint* joint)
  252. {
  253. auto it = std::find(_joints.begin(), _joints.end(), joint);
  254. if (it != _joints.end())
  255. {
  256. _joints.erase(it);
  257. }
  258. }
  259. void PhysicsBody::setDynamic(bool dynamic)
  260. {
  261. if (dynamic != _dynamic)
  262. {
  263. _dynamic = dynamic;
  264. if (dynamic)
  265. {
  266. cpBodySetType(_cpBody, CP_BODY_TYPE_DYNAMIC);
  267. internalBodySetMass(_cpBody, _mass);
  268. cpBodySetMoment(_cpBody, _moment);
  269. }
  270. else
  271. {
  272. cpBodySetType(_cpBody, CP_BODY_TYPE_KINEMATIC);
  273. }
  274. }
  275. }
  276. void PhysicsBody::setRotationEnable(bool enable)
  277. {
  278. if (_rotationEnabled != enable)
  279. {
  280. cpBodySetMoment(_cpBody, enable ? _moment : PHYSICS_INFINITY);
  281. _rotationEnabled = enable;
  282. }
  283. }
  284. void PhysicsBody::setGravityEnable(bool enable)
  285. {
  286. _gravityEnabled = enable;
  287. }
  288. void PhysicsBody::setRotation(float rotation)
  289. {
  290. _recordedRotation = rotation;
  291. _recordedAngle = - (rotation + _rotationOffset) * (M_PI / 180.0);
  292. cpBodySetAngle(_cpBody, _recordedAngle);
  293. }
  294. void PhysicsBody::setScale(float scaleX, float scaleY)
  295. {
  296. for (auto& shape : _shapes)
  297. {
  298. _area -= shape->getArea();
  299. if (!_massSetByUser)
  300. addMass(-shape->getMass());
  301. if (!_momentSetByUser)
  302. addMoment(-shape->getMoment());
  303. shape->setScale(scaleX, scaleY);
  304. _area += shape->getArea();
  305. if (!_massSetByUser)
  306. addMass(shape->getMass());
  307. if (!_momentSetByUser)
  308. addMoment(shape->getMoment());
  309. }
  310. }
  311. void PhysicsBody::setPosition(float positionX, float positionY)
  312. {
  313. cpVect tt;
  314. tt.x = positionX + _positionOffset.x;
  315. tt.y = positionY + _positionOffset.y;
  316. cpBodySetPosition(_cpBody, tt);
  317. }
  318. Vec2 PhysicsBody::getPosition() const
  319. {
  320. cpVect tt = cpBodyGetPosition(_cpBody);
  321. return Vec2(tt.x - _positionOffset.x, tt.y - _positionOffset.y);
  322. }
  323. void PhysicsBody::setPositionOffset(const Vec2& position)
  324. {
  325. if (!_positionOffset.equals(position))
  326. {
  327. Vec2 pos = getPosition();
  328. _positionOffset = position;
  329. setPosition(pos.x, pos.y);
  330. }
  331. }
  332. float PhysicsBody::getRotation()
  333. {
  334. if (_recordedAngle != cpBodyGetAngle(_cpBody)) {
  335. _recordedAngle = cpBodyGetAngle(_cpBody);
  336. _recordedRotation = - _recordedAngle * 180.0 / M_PI - _rotationOffset;
  337. }
  338. return _recordedRotation;
  339. }
  340. PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* = true*/)
  341. {
  342. if (shape == nullptr) return nullptr;
  343. // add shape to body
  344. if (_shapes.getIndex(shape) == -1)
  345. {
  346. shape->setBody(this);
  347. // calculate the area, mass, and density
  348. // area must update before mass, because the density changes depend on it.
  349. if (addMassAndMoment)
  350. {
  351. _area += shape->getArea();
  352. addMass(shape->getMass());
  353. addMoment(shape->getMoment());
  354. }
  355. if (_world && cpBodyGetSpace(_cpBody))
  356. {
  357. _world->addShape(shape);
  358. }
  359. _shapes.pushBack(shape);
  360. }
  361. return shape;
  362. }
  363. void PhysicsBody::applyForce(const Vec2& force, const Vec2& offset)
  364. {
  365. if (_dynamic && _mass != PHYSICS_INFINITY)
  366. {
  367. cpBodyApplyForceAtLocalPoint(_cpBody, PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset));
  368. }
  369. }
  370. void PhysicsBody::resetForces()
  371. {
  372. cpBodySetForce(_cpBody, PhysicsHelper::point2cpv(Vec2(0,0)));
  373. }
  374. void PhysicsBody::applyImpulse(const Vec2& impulse, const Vec2& offset)
  375. {
  376. cpBodyApplyImpulseAtLocalPoint(_cpBody, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset));
  377. }
  378. void PhysicsBody::applyTorque(float torque)
  379. {
  380. cpBodySetTorque(_cpBody, torque);
  381. }
  382. void PhysicsBody::setMass(float mass)
  383. {
  384. if (mass <= 0)
  385. {
  386. return;
  387. }
  388. _mass = mass;
  389. _massDefault = false;
  390. _massSetByUser = true;
  391. // update density
  392. if (_mass == PHYSICS_INFINITY)
  393. {
  394. _density = PHYSICS_INFINITY;
  395. }
  396. else
  397. {
  398. if (_area > 0)
  399. {
  400. _density = _mass / _area;
  401. }else
  402. {
  403. _density = 0;
  404. }
  405. }
  406. // the static body's mass and moment is always infinity
  407. if (_dynamic)
  408. {
  409. internalBodySetMass(_cpBody, _mass);
  410. }
  411. }
  412. void PhysicsBody::addMass(float mass)
  413. {
  414. if (mass == PHYSICS_INFINITY)
  415. {
  416. _mass = PHYSICS_INFINITY;
  417. _massDefault = false;
  418. _density = PHYSICS_INFINITY;
  419. }
  420. else if (mass == -PHYSICS_INFINITY)
  421. {
  422. return;
  423. }
  424. else
  425. {
  426. if (_massDefault)
  427. {
  428. _mass = 0;
  429. _massDefault = false;
  430. }
  431. if (_mass + mass > 0)
  432. {
  433. _mass += mass;
  434. }else
  435. {
  436. _mass = MASS_DEFAULT;
  437. _massDefault = true;
  438. }
  439. if (_area > 0)
  440. {
  441. _density = _mass / _area;
  442. }
  443. else
  444. {
  445. _density = 0;
  446. }
  447. }
  448. // the static body's mass and moment is always infinity
  449. if (_dynamic)
  450. {
  451. internalBodySetMass(_cpBody, _mass);
  452. }
  453. }
  454. void PhysicsBody::addMoment(float moment)
  455. {
  456. if (moment == PHYSICS_INFINITY)
  457. {
  458. // if moment is PHYSICS_INFINITY, the moment of the body will become PHYSICS_INFINITY
  459. _moment = PHYSICS_INFINITY;
  460. _momentDefault = false;
  461. }
  462. else if (moment == -PHYSICS_INFINITY)
  463. {
  464. return;
  465. }
  466. else
  467. {
  468. // if moment of the body is PHYSICS_INFINITY is has no effect
  469. if (_moment != PHYSICS_INFINITY)
  470. {
  471. if (_momentDefault)
  472. {
  473. _moment = 0;
  474. _momentDefault = false;
  475. }
  476. if (_moment + moment > 0)
  477. {
  478. _moment += moment;
  479. }
  480. else
  481. {
  482. _moment = MOMENT_DEFAULT;
  483. _momentDefault = true;
  484. }
  485. }
  486. }
  487. // the static body's mass and moment is always infinity
  488. if (_rotationEnabled && _dynamic)
  489. {
  490. cpBodySetMoment(_cpBody, _moment);
  491. }
  492. }
  493. void PhysicsBody::setVelocity(const Vec2& velocity)
  494. {
  495. if (cpBodyGetType(_cpBody) == CP_BODY_TYPE_STATIC)
  496. {
  497. CCLOG("physics warning: you can't set velocity for a static body.");
  498. return;
  499. }
  500. cpBodySetVelocity(_cpBody, PhysicsHelper::point2cpv(velocity));
  501. }
  502. Vec2 PhysicsBody::getVelocity()
  503. {
  504. return PhysicsHelper::cpv2point(cpBodyGetVelocity(_cpBody));
  505. }
  506. Vec2 PhysicsBody::getVelocityAtLocalPoint(const Vec2& point)
  507. {
  508. return PhysicsHelper::cpv2point(cpBodyGetVelocityAtLocalPoint(_cpBody, PhysicsHelper::point2cpv(point)));
  509. }
  510. Vec2 PhysicsBody::getVelocityAtWorldPoint(const Vec2& point)
  511. {
  512. return PhysicsHelper::cpv2point(cpBodyGetVelocityAtWorldPoint(_cpBody, PhysicsHelper::point2cpv(point)));
  513. }
  514. void PhysicsBody::setAngularVelocity(float velocity)
  515. {
  516. if (cpBodyGetType(_cpBody) == CP_BODY_TYPE_STATIC)
  517. {
  518. CCLOG("physics warning: you can't set angular velocity for a static body.");
  519. return;
  520. }
  521. cpBodySetAngularVelocity(_cpBody, velocity);
  522. }
  523. float PhysicsBody::getAngularVelocity()
  524. {
  525. return PhysicsHelper::cpfloat2float(cpBodyGetAngularVelocity(_cpBody));
  526. }
  527. void PhysicsBody::setVelocityLimit(float limit)
  528. {
  529. _velocityLimit = limit;
  530. }
  531. float PhysicsBody::getVelocityLimit()
  532. {
  533. return _velocityLimit;
  534. }
  535. void PhysicsBody::setAngularVelocityLimit(float limit)
  536. {
  537. _angularVelocityLimit = limit;
  538. }
  539. float PhysicsBody::getAngularVelocityLimit()
  540. {
  541. return _angularVelocityLimit;
  542. }
  543. void PhysicsBody::setMoment(float moment)
  544. {
  545. _moment = moment;
  546. _momentDefault = false;
  547. _momentSetByUser = true;
  548. // the static body's mass and moment is always infinity
  549. if (_rotationEnabled && _dynamic)
  550. {
  551. cpBodySetMoment(_cpBody, _moment);
  552. }
  553. }
  554. PhysicsShape* PhysicsBody::getShape(int tag) const
  555. {
  556. for (auto& shape : _shapes)
  557. {
  558. if (shape->getTag() == tag)
  559. {
  560. return shape;
  561. }
  562. }
  563. return nullptr;
  564. }
  565. void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/)
  566. {
  567. for (auto& shape : _shapes)
  568. {
  569. if (shape->getTag() == tag)
  570. {
  571. removeShape(shape, reduceMassAndMoment);
  572. return;
  573. }
  574. }
  575. }
  576. void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = true*/)
  577. {
  578. if (_shapes.getIndex(shape) != -1)
  579. {
  580. // deduce the area, mass and moment
  581. // area must update before mass, because the density changes depend on it.
  582. if (reduceMassAndMoment)
  583. {
  584. _area -= shape->getArea();
  585. addMass(-shape->getMass());
  586. addMoment(-shape->getMoment());
  587. }
  588. //remove
  589. if (_world)
  590. {
  591. _world->removeShape(shape);
  592. }
  593. // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call.
  594. shape->_body = nullptr;
  595. shape->setBody(nullptr);
  596. _shapes.eraseObject(shape);
  597. }
  598. }
  599. void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/)
  600. {
  601. for (auto& child : _shapes)
  602. {
  603. PhysicsShape* shape = dynamic_cast<PhysicsShape*>(child);
  604. // deduce the area, mass and moment
  605. // area must update before mass, because the density changes depend on it.
  606. if (reduceMassAndMoment)
  607. {
  608. _area -= shape->getArea();
  609. addMass(-shape->getMass());
  610. addMoment(-shape->getMoment());
  611. }
  612. if (_world)
  613. {
  614. _world->removeShape(shape);
  615. }
  616. // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call.
  617. shape->_body = nullptr;
  618. shape->setBody(nullptr);
  619. }
  620. _shapes.clear();
  621. }
  622. void PhysicsBody::removeFromWorld()
  623. {
  624. removeFromPhysicsWorld();
  625. }
  626. void PhysicsBody::setEnabled(bool enable)
  627. {
  628. if (_enabled != enable)
  629. {
  630. _enabled = enable;
  631. if (_world)
  632. {
  633. if (enable)
  634. {
  635. _world->addBodyOrDelay(this);
  636. }else
  637. {
  638. _world->removeBodyOrDelay(this);
  639. }
  640. }
  641. }
  642. }
  643. bool PhysicsBody::isResting() const
  644. {
  645. return cpBodyIsSleeping(_cpBody) != cpFalse;
  646. }
  647. void PhysicsBody::setResting(bool rest) const
  648. {
  649. if (rest && !isResting())
  650. {
  651. cpBodySleep(_cpBody);
  652. }
  653. else if(!rest && isResting())
  654. {
  655. cpBodyActivate(_cpBody);
  656. }
  657. }
  658. void PhysicsBody::update(float delta)
  659. {
  660. // damping compute
  661. if (_isDamping && _dynamic && !isResting())
  662. {
  663. _cpBody->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f);
  664. _cpBody->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f);
  665. _cpBody->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f);
  666. }
  667. }
  668. void PhysicsBody::setCategoryBitmask(int bitmask)
  669. {
  670. for (auto& shape : _shapes)
  671. {
  672. shape->setCategoryBitmask(bitmask);
  673. }
  674. }
  675. int PhysicsBody::getCategoryBitmask() const
  676. {
  677. if (!_shapes.empty())
  678. {
  679. return _shapes.front()->getCategoryBitmask();
  680. }
  681. else
  682. {
  683. return UINT_MAX;
  684. }
  685. }
  686. void PhysicsBody::setContactTestBitmask(int bitmask)
  687. {
  688. for (auto& shape : _shapes)
  689. {
  690. shape->setContactTestBitmask(bitmask);
  691. }
  692. }
  693. int PhysicsBody::getContactTestBitmask() const
  694. {
  695. if (!_shapes.empty())
  696. {
  697. return _shapes.front()->getContactTestBitmask();
  698. }
  699. else
  700. {
  701. return 0x00000000;
  702. }
  703. }
  704. void PhysicsBody::setCollisionBitmask(int bitmask)
  705. {
  706. for (auto& shape : _shapes)
  707. {
  708. shape->setCollisionBitmask(bitmask);
  709. }
  710. }
  711. int PhysicsBody::getCollisionBitmask() const
  712. {
  713. if (!_shapes.empty())
  714. {
  715. return _shapes.front()->getCollisionBitmask();
  716. }
  717. else
  718. {
  719. return UINT_MAX;
  720. }
  721. }
  722. void PhysicsBody::setGroup(int group)
  723. {
  724. for (auto& shape : _shapes)
  725. {
  726. shape->setGroup(group);
  727. }
  728. }
  729. int PhysicsBody::getGroup() const
  730. {
  731. if (!_shapes.empty())
  732. {
  733. return _shapes.front()->getGroup();
  734. }
  735. else
  736. {
  737. return 0;
  738. }
  739. }
  740. void PhysicsBody::setRotationOffset(float rotation)
  741. {
  742. if (std::abs(_rotationOffset - rotation) > 0.5f)
  743. {
  744. float rot = getRotation();
  745. _rotationOffset = rotation;
  746. setRotation(rot);
  747. }
  748. }
  749. Vec2 PhysicsBody::world2Local(const Vec2& point)
  750. {
  751. return PhysicsHelper::cpv2point(cpBodyWorldToLocal(_cpBody, PhysicsHelper::point2cpv(point)));
  752. }
  753. Vec2 PhysicsBody::local2World(const Vec2& point)
  754. {
  755. return PhysicsHelper::cpv2point(cpBodyLocalToWorld(_cpBody, PhysicsHelper::point2cpv(point)));
  756. }
  757. void PhysicsBody::beforeSimulation(const Mat4& parentToWorldTransform, const Mat4& nodeToWorldTransform, float scaleX, float scaleY, float rotation)
  758. {
  759. if (_recordScaleX != scaleX || _recordScaleY != scaleY)
  760. {
  761. _recordScaleX = scaleX;
  762. _recordScaleY = scaleY;
  763. setScale(scaleX, scaleY);
  764. }
  765. // set rotation
  766. if (_recordedRotation != rotation)
  767. {
  768. setRotation(rotation);
  769. }
  770. // set position
  771. auto worldPosition = _ownerCenterOffset;
  772. nodeToWorldTransform.transformVector(worldPosition.x, worldPosition.y, worldPosition.z, 1.f, &worldPosition);
  773. setPosition(worldPosition.x, worldPosition.y);
  774. _recordPosX = worldPosition.x;
  775. _recordPosY = worldPosition.y;
  776. if (_owner->getAnchorPoint() != Vec2::ANCHOR_MIDDLE)
  777. {
  778. parentToWorldTransform.getInversed().transformVector(worldPosition.x, worldPosition.y, worldPosition.z, 1.f, &worldPosition);
  779. _offset.x = worldPosition.x - _owner->getPositionX();
  780. _offset.y = worldPosition.y - _owner->getPositionY();
  781. }
  782. }
  783. void PhysicsBody::afterSimulation(const Mat4& parentToWorldTransform, float parentRotation)
  784. {
  785. // set Node position
  786. auto tmp = getPosition();
  787. Vec3 positionInParent(tmp.x, tmp.y, 0.f);
  788. if (_recordPosX != positionInParent.x || _recordPosY != positionInParent.y)
  789. {
  790. parentToWorldTransform.getInversed().transformVector(positionInParent.x, positionInParent.y, positionInParent.z, 1.f, &positionInParent);
  791. _owner->setPosition(positionInParent.x - _offset.x, positionInParent.y - _offset.y);
  792. }
  793. // set Node rotation
  794. _owner->setRotation(getRotation() - parentRotation);
  795. }
  796. void PhysicsBody::onEnter()
  797. {
  798. addToPhysicsWorld();
  799. }
  800. void PhysicsBody::onExit()
  801. {
  802. removeFromPhysicsWorld();
  803. }
  804. void PhysicsBody::onAdd()
  805. {
  806. _owner->_physicsBody = this;
  807. auto contentSize = _owner->getContentSize();
  808. _ownerCenterOffset.x = 0.5f * contentSize.width;
  809. _ownerCenterOffset.y = 0.5f * contentSize.height;
  810. setRotationOffset(_owner->getRotation());
  811. // component may be added after onEnter() has been invoked, so we should add
  812. // this line to make sure physics body is added to physics world
  813. addToPhysicsWorld();
  814. }
  815. void PhysicsBody::onRemove()
  816. {
  817. CCASSERT(_owner != nullptr, "_owner can't be nullptr");
  818. removeFromPhysicsWorld();
  819. _owner->_physicsBody = nullptr;
  820. }
  821. void PhysicsBody::addToPhysicsWorld()
  822. {
  823. if (_owner)
  824. {
  825. auto scene = _owner->getScene();
  826. if (scene)
  827. scene->getPhysicsWorld()->addBody(this);
  828. }
  829. }
  830. void PhysicsBody::removeFromPhysicsWorld()
  831. {
  832. if (_owner)
  833. {
  834. auto scene = _owner->getScene();
  835. if (scene)
  836. scene->getPhysicsWorld()->removeBody(this);
  837. }
  838. }
  839. NS_CC_END
  840. #endif // CC_USE_PHYSICS