PhysicsCharacter.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. /**
  2. * PhysicsCharacter.cpp
  3. *
  4. * Much of the collision detection code for this implementation is based off the
  5. * btbtKinematicCharacterController class from Bullet Physics 2.7.6.
  6. */
  7. #include "Base.h"
  8. #include "PhysicsCharacter.h"
  9. #include "Scene.h"
  10. #include "Game.h"
  11. #include "PhysicsController.h"
  12. namespace gameplay
  13. {
  14. /**
  15. * @script{ignore}
  16. */
  17. class ClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
  18. {
  19. public:
  20. /**
  21. * @see btCollisionWorld::ClosestConvexResultCallback::ClosestConvexResultCallback
  22. */
  23. ClosestNotMeConvexResultCallback(PhysicsCollisionObject* me, const btVector3& up, btScalar minSlopeDot)
  24. : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)), _me(me), _up(up), _minSlopeDot(minSlopeDot)
  25. {
  26. }
  27. /**
  28. * @see btCollisionWorld::ClosestConvexResultCallback::addSingleResult
  29. */
  30. btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)
  31. {
  32. PhysicsCollisionObject* object = reinterpret_cast<PhysicsCollisionObject*>(convexResult.m_hitCollisionObject->getUserPointer());
  33. GP_ASSERT(object);
  34. if (object == _me || object->getType() == PhysicsCollisionObject::GHOST_OBJECT)
  35. return 1.0f;
  36. return ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
  37. }
  38. protected:
  39. PhysicsCollisionObject* _me;
  40. const btVector3 _up;
  41. btScalar _minSlopeDot;
  42. };
  43. PhysicsCharacter::PhysicsCharacter(Node* node, const PhysicsCollisionShape::Definition& shape, float mass)
  44. : PhysicsGhostObject(node, shape), _moveVelocity(0,0,0), _forwardVelocity(0.0f), _rightVelocity(0.0f),
  45. _verticalVelocity(0, 0, 0), _currentVelocity(0,0,0), _normalizedVelocity(0,0,0),
  46. _colliding(false), _collisionNormal(0,0,0), _currentPosition(0,0,0), _stepHeight(0.1f),
  47. _slopeAngle(0.0f), _cosSlopeAngle(0.0f), _physicsEnabled(true), _mass(mass), _actionInterface(NULL)
  48. {
  49. setMaxSlopeAngle(45.0f);
  50. // Set the collision flags on the ghost object to indicate it's a character.
  51. GP_ASSERT(_ghostObject);
  52. _ghostObject->setCollisionFlags(_ghostObject->getCollisionFlags() | btCollisionObject::CF_CHARACTER_OBJECT | btCollisionObject::CF_NO_CONTACT_RESPONSE);
  53. // Register ourselves as an action on the physics world so we are called back during physics ticks.
  54. GP_ASSERT(Game::getInstance()->getPhysicsController() && Game::getInstance()->getPhysicsController()->_world);
  55. _actionInterface = new ActionInterface(this);
  56. Game::getInstance()->getPhysicsController()->_world->addAction(_actionInterface);
  57. }
  58. PhysicsCharacter::~PhysicsCharacter()
  59. {
  60. // Unregister ourselves as action from world.
  61. GP_ASSERT(Game::getInstance()->getPhysicsController() && Game::getInstance()->getPhysicsController()->_world);
  62. Game::getInstance()->getPhysicsController()->_world->removeAction(_actionInterface);
  63. SAFE_DELETE(_actionInterface);
  64. }
  65. PhysicsCharacter* PhysicsCharacter::create(Node* node, Properties* properties)
  66. {
  67. // Check if the properties is valid and has a valid namespace.
  68. if (!properties || !(strcmp(properties->getNamespace(), "collisionObject") == 0))
  69. {
  70. GP_ERROR("Failed to load physics character from properties object: must be non-null object and have namespace equal to 'collisionObject'.");
  71. return NULL;
  72. }
  73. // Check that the type is specified and correct.
  74. const char* type = properties->getString("type");
  75. if (!type)
  76. {
  77. GP_ERROR("Failed to load physics character from properties object; required attribute 'type' is missing.");
  78. return NULL;
  79. }
  80. if (strcmp(type, "CHARACTER") != 0)
  81. {
  82. GP_ERROR("Failed to load physics character from properties object; attribute 'type' must be equal to 'CHARACTER'.");
  83. return NULL;
  84. }
  85. // Load the physics collision shape definition.
  86. PhysicsCollisionShape::Definition* shape = PhysicsCollisionShape::Definition::create(node, properties);
  87. if (shape == NULL)
  88. {
  89. GP_ERROR("Failed to create collision shape during physics character creation.");
  90. return NULL;
  91. }
  92. // Load the character's parameters.
  93. properties->rewind();
  94. float mass = 1.0f;
  95. float maxStepHeight = 0.1f;
  96. float maxSlopeAngle = 0.0f;
  97. const char* name = NULL;
  98. while ((name = properties->getNextProperty()) != NULL)
  99. {
  100. if (strcmp(name, "mass") == 0)
  101. {
  102. mass = properties->getFloat();
  103. }
  104. else if (strcmp(name, "maxStepHeight") == 0)
  105. {
  106. maxStepHeight = properties->getFloat();
  107. }
  108. else if (strcmp(name, "maxSlopeAngle") == 0)
  109. {
  110. maxSlopeAngle = properties->getFloat();
  111. }
  112. else
  113. {
  114. // Ignore this case (the attributes for the character's collision shape would end up here).
  115. }
  116. }
  117. // Create the physics character.
  118. PhysicsCharacter* character = new PhysicsCharacter(node, *shape, mass);
  119. character->setMaxStepHeight(maxStepHeight);
  120. character->setMaxSlopeAngle(maxSlopeAngle);
  121. SAFE_DELETE(shape);
  122. return character;
  123. }
  124. PhysicsCollisionObject::Type PhysicsCharacter::getType() const
  125. {
  126. return PhysicsCollisionObject::CHARACTER;
  127. }
  128. btCollisionObject* PhysicsCharacter::getCollisionObject() const
  129. {
  130. return _ghostObject;
  131. }
  132. bool PhysicsCharacter::isPhysicsEnabled() const
  133. {
  134. return _physicsEnabled;
  135. }
  136. void PhysicsCharacter::setPhysicsEnabled(bool enabled)
  137. {
  138. _physicsEnabled = enabled;
  139. }
  140. float PhysicsCharacter::getMaxStepHeight() const
  141. {
  142. return _stepHeight;
  143. }
  144. void PhysicsCharacter::setMaxStepHeight(float height)
  145. {
  146. _stepHeight = height;
  147. }
  148. float PhysicsCharacter::getMaxSlopeAngle() const
  149. {
  150. return _slopeAngle;
  151. }
  152. void PhysicsCharacter::setMaxSlopeAngle(float angle)
  153. {
  154. _slopeAngle = angle;
  155. _cosSlopeAngle = std::cos(MATH_DEG_TO_RAD(angle));
  156. }
  157. void PhysicsCharacter::setVelocity(const Vector3& velocity)
  158. {
  159. _moveVelocity.setValue(velocity.x, velocity.y, velocity.z);
  160. }
  161. void PhysicsCharacter::setVelocity(float x, float y, float z)
  162. {
  163. _moveVelocity.setValue(x, y, z);
  164. }
  165. void PhysicsCharacter::rotate(const Vector3& axis, float angle)
  166. {
  167. GP_ASSERT(_node);
  168. _node->rotate(axis, angle);
  169. }
  170. void PhysicsCharacter::rotate(const Quaternion& rotation)
  171. {
  172. GP_ASSERT(_node);
  173. _node->rotate(rotation);
  174. }
  175. void PhysicsCharacter::setRotation(const Vector3& axis, float angle)
  176. {
  177. GP_ASSERT(_node);
  178. _node->setRotation(axis, angle);
  179. }
  180. void PhysicsCharacter::setRotation(const Quaternion& rotation)
  181. {
  182. GP_ASSERT(_node);
  183. _node->setRotation(rotation);
  184. }
  185. void PhysicsCharacter::setForwardVelocity(float velocity)
  186. {
  187. _forwardVelocity = velocity;
  188. }
  189. void PhysicsCharacter::setRightVelocity(float velocity)
  190. {
  191. _rightVelocity = velocity;
  192. }
  193. Vector3 PhysicsCharacter::getCurrentVelocity() const
  194. {
  195. Vector3 v(_currentVelocity.x(), _currentVelocity.y(), _currentVelocity.z());
  196. v.x += _verticalVelocity.x();
  197. v.y += _verticalVelocity.y();
  198. v.z += _verticalVelocity.z();
  199. return v;
  200. }
  201. void PhysicsCharacter::jump(float height)
  202. {
  203. // TODO: Add support for different jump modes (i.e. double jump, changing direction in air, holding down jump button for extra height, etc)
  204. if (!_verticalVelocity.isZero())
  205. return;
  206. // v = sqrt(v0^2 + 2 a s)
  207. // v0 == initial velocity (zero for jumping)
  208. // a == acceleration (inverse gravity)
  209. // s == linear displacement (height)
  210. GP_ASSERT(Game::getInstance()->getPhysicsController());
  211. Vector3 jumpVelocity = -Game::getInstance()->getPhysicsController()->getGravity() * height * 2.0f;
  212. jumpVelocity.set(
  213. jumpVelocity.x == 0 ? 0 : std::sqrt(jumpVelocity.x),
  214. jumpVelocity.y == 0 ? 0 : std::sqrt(jumpVelocity.y),
  215. jumpVelocity.z == 0 ? 0 : std::sqrt(jumpVelocity.z));
  216. _verticalVelocity += BV(jumpVelocity);
  217. }
  218. void PhysicsCharacter::updateCurrentVelocity()
  219. {
  220. GP_ASSERT(_node);
  221. Vector3 temp;
  222. btScalar velocity2 = 0;
  223. // Reset velocity vector.
  224. _normalizedVelocity.setValue(0, 0, 0);
  225. // Add movement velocity contribution.
  226. if (!_moveVelocity.isZero())
  227. {
  228. _normalizedVelocity = _moveVelocity;
  229. velocity2 = _moveVelocity.length2();
  230. }
  231. // Add forward velocity contribution.
  232. if (_forwardVelocity != 0)
  233. {
  234. _node->getWorldMatrix().getForwardVector(&temp);
  235. temp.normalize();
  236. temp *= -_forwardVelocity;
  237. _normalizedVelocity += btVector3(temp.x, temp.y, temp.z);
  238. velocity2 = std::max(std::fabs(velocity2), std::fabs(_forwardVelocity*_forwardVelocity));
  239. }
  240. // Add right velocity contribution.
  241. if (_rightVelocity != 0)
  242. {
  243. _node->getWorldMatrix().getRightVector(&temp);
  244. temp.normalize();
  245. temp *= _rightVelocity;
  246. _normalizedVelocity += btVector3(temp.x, temp.y, temp.z);
  247. velocity2 = std::max(std::fabs(velocity2), std::fabs(_rightVelocity*_rightVelocity));
  248. }
  249. // Compute final combined movement vectors
  250. if (_normalizedVelocity.isZero())
  251. {
  252. _currentVelocity.setZero();
  253. }
  254. else
  255. {
  256. _normalizedVelocity.normalize();
  257. _currentVelocity = _normalizedVelocity * std::sqrt(velocity2);
  258. }
  259. }
  260. void PhysicsCharacter::stepUp(btCollisionWorld* collisionWorld, btScalar time)
  261. {
  262. btVector3 targetPosition(_currentPosition);
  263. if (_verticalVelocity.isZero())
  264. {
  265. // Simply increase our poisiton by step height to enable us
  266. // to smoothly move over steps.
  267. targetPosition += btVector3(0, _stepHeight, 0);
  268. }
  269. // TODO: Convex sweep test to ensure we didn't hit anything during the step up.
  270. _currentPosition = targetPosition;
  271. }
  272. void PhysicsCharacter::stepForwardAndStrafe(btCollisionWorld* collisionWorld, float time)
  273. {
  274. updateCurrentVelocity();
  275. // Calculate final velocity
  276. btVector3 velocity(_currentVelocity);
  277. velocity *= time; // since velocity is in meters per second
  278. if (velocity.isZero())
  279. {
  280. // No velocity, so we aren't moving
  281. return;
  282. }
  283. // Translate the target position by the velocity vector (already scaled by t)
  284. btVector3 targetPosition = _currentPosition + velocity;
  285. // If physics is disabled, simply update current position without checking collisions
  286. if (!_physicsEnabled)
  287. {
  288. _currentPosition = targetPosition;
  289. return;
  290. }
  291. // Check for collisions by performing a bullet convex sweep test
  292. btTransform start;
  293. btTransform end;
  294. start.setIdentity();
  295. end.setIdentity();
  296. btScalar fraction = 1.0;
  297. btScalar distance2;
  298. if (_colliding && (_normalizedVelocity.dot(_collisionNormal) > btScalar(0.0)))
  299. {
  300. updateTargetPositionFromCollision(targetPosition, _collisionNormal);
  301. }
  302. int maxIter = 10;
  303. GP_ASSERT(_ghostObject && _ghostObject->getBroadphaseHandle());
  304. GP_ASSERT(_collisionShape);
  305. GP_ASSERT(collisionWorld);
  306. GP_ASSERT(Game::getInstance()->getPhysicsController());
  307. while (fraction > btScalar(0.01) && maxIter-- > 0)
  308. {
  309. start.setOrigin(_currentPosition);
  310. end.setOrigin(targetPosition);
  311. btVector3 sweepDirNegative(_currentPosition - targetPosition);
  312. ClosestNotMeConvexResultCallback callback(this, sweepDirNegative, btScalar(0.0));
  313. callback.m_collisionFilterGroup = _ghostObject->getBroadphaseHandle()->m_collisionFilterGroup;
  314. callback.m_collisionFilterMask = _ghostObject->getBroadphaseHandle()->m_collisionFilterMask;
  315. _ghostObject->convexSweepTest(static_cast<btConvexShape*>(_collisionShape->getShape()), start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  316. fraction -= callback.m_closestHitFraction;
  317. if (callback.hasHit())
  318. {
  319. Vector3 normal(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  320. PhysicsCollisionObject* o = Game::getInstance()->getPhysicsController()->getCollisionObject(callback.m_hitCollisionObject);
  321. GP_ASSERT(o);
  322. if (o->getType() == PhysicsCollisionObject::RIGID_BODY && o->isDynamic())
  323. {
  324. PhysicsRigidBody* rb = static_cast<PhysicsRigidBody*>(o);
  325. GP_ASSERT(rb);
  326. normal.normalize();
  327. rb->applyImpulse(_mass * -normal * velocity.length());
  328. }
  329. updateTargetPositionFromCollision(targetPosition, callback.m_hitNormalWorld);
  330. btVector3 currentDir = targetPosition - _currentPosition;
  331. distance2 = currentDir.length2();
  332. if (distance2 > FLT_EPSILON)
  333. {
  334. currentDir.normalize();
  335. // If velocity is against original velocity, stop to avoid tiny oscilations in sloping corners.
  336. if (currentDir.dot(_normalizedVelocity) <= btScalar(0.0))
  337. {
  338. break;
  339. }
  340. }
  341. }
  342. else
  343. {
  344. // Nothing in our way
  345. break;
  346. }
  347. }
  348. _currentPosition = targetPosition;
  349. }
  350. void PhysicsCharacter::stepDown(btCollisionWorld* collisionWorld, btScalar time)
  351. {
  352. GP_ASSERT(Game::getInstance()->getPhysicsController() && Game::getInstance()->getPhysicsController()->_world);
  353. GP_ASSERT(_ghostObject && _ghostObject->getBroadphaseHandle());
  354. GP_ASSERT(_collisionShape);
  355. GP_ASSERT(collisionWorld);
  356. // Contribute gravity to vertical velocity.
  357. btVector3 gravity = Game::getInstance()->getPhysicsController()->_world->getGravity();
  358. _verticalVelocity += (gravity * time);
  359. // Compute new position from vertical velocity.
  360. btVector3 targetPosition = _currentPosition + (_verticalVelocity * time);
  361. targetPosition -= btVector3(0, _stepHeight, 0);
  362. // Perform a convex sweep test between current and target position.
  363. btTransform start;
  364. btTransform end;
  365. start.setIdentity();
  366. end.setIdentity();
  367. btScalar fraction = 1.0;
  368. int maxIter = 10;
  369. while (fraction > btScalar(0.01) && maxIter-- > 0)
  370. {
  371. start.setOrigin(_currentPosition);
  372. end.setOrigin(targetPosition);
  373. btVector3 sweepDirNegative(_currentPosition - targetPosition);
  374. ClosestNotMeConvexResultCallback callback(this, sweepDirNegative, 0.0);
  375. callback.m_collisionFilterGroup = _ghostObject->getBroadphaseHandle()->m_collisionFilterGroup;
  376. callback.m_collisionFilterMask = _ghostObject->getBroadphaseHandle()->m_collisionFilterMask;
  377. _ghostObject->convexSweepTest(static_cast<btConvexShape*>(_collisionShape->getShape()), start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  378. fraction -= callback.m_closestHitFraction;
  379. if (callback.hasHit())
  380. {
  381. // Collision detected, fix it.
  382. Vector3 normal(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  383. normal.normalize();
  384. float dot = normal.dot(Vector3::unitY());
  385. if (dot > 1.0f - MATH_EPSILON)
  386. {
  387. targetPosition.setInterpolate3(_currentPosition, targetPosition, callback.m_closestHitFraction);
  388. // Zero out fall velocity when we hit an object going straight down.
  389. _verticalVelocity.setZero();
  390. break;
  391. }
  392. else
  393. {
  394. PhysicsCollisionObject* o = Game::getInstance()->getPhysicsController()->getCollisionObject(callback.m_hitCollisionObject);
  395. GP_ASSERT(o);
  396. if (o->getType() == PhysicsCollisionObject::RIGID_BODY && o->isDynamic())
  397. {
  398. PhysicsRigidBody* rb = static_cast<PhysicsRigidBody*>(o);
  399. GP_ASSERT(rb);
  400. normal.normalize();
  401. rb->applyImpulse(_mass * -normal * sqrt(BV(normal).dot(_verticalVelocity)));
  402. }
  403. updateTargetPositionFromCollision(targetPosition, BV(normal));
  404. }
  405. }
  406. else
  407. {
  408. // Nothing is in the way.
  409. break;
  410. }
  411. }
  412. // Calculate what the vertical velocity actually is.
  413. // In cases where the character might not actually be able to move down,
  414. // but isn't intersecting with an object straight down either, we don't
  415. // want to keep increasing the vertical velocity until the character
  416. // randomly drops through the floor when it can finally move due to its
  417. // vertical velocity having such a great magnitude.
  418. if (!_verticalVelocity.isZero() && time > 0.0f)
  419. _verticalVelocity = ((targetPosition + btVector3(0.0, _stepHeight, 0.0)) - _currentPosition) / time;
  420. _currentPosition = targetPosition;
  421. }
  422. /*
  423. * Returns the reflection direction of a ray going 'direction' hitting a surface with normal 'normal'.
  424. */
  425. static btVector3 computeReflectionDirection(const btVector3& direction, const btVector3& normal)
  426. {
  427. return direction - (btScalar(2.0) * direction.dot(normal)) * normal;
  428. }
  429. /*
  430. * Returns the portion of 'direction' that is parallel to 'normal'.
  431. */
  432. static btVector3 parallelComponent(const btVector3& direction, const btVector3& normal)
  433. {
  434. btScalar magnitude = direction.dot(normal);
  435. return normal * magnitude;
  436. }
  437. /*
  438. * Returns the portion of 'direction' that is perpindicular to 'normal'.
  439. */
  440. static btVector3 perpindicularComponent(const btVector3& direction, const btVector3& normal)
  441. {
  442. return direction - parallelComponent(direction, normal);
  443. }
  444. void PhysicsCharacter::updateTargetPositionFromCollision(btVector3& targetPosition, const btVector3& collisionNormal)
  445. {
  446. btVector3 movementDirection = targetPosition - _currentPosition;
  447. btScalar movementLength = movementDirection.length();
  448. if (movementLength > FLT_EPSILON)
  449. {
  450. movementDirection.normalize();
  451. btVector3 reflectDir = computeReflectionDirection(movementDirection, collisionNormal);
  452. reflectDir.normalize();
  453. btVector3 perpindicularDir = perpindicularComponent(reflectDir, collisionNormal);
  454. targetPosition = _currentPosition;
  455. // Disallow the character from moving up during collision recovery (using an arbitrary reasonable epsilon).
  456. // Note that this will need to be generalized to allow for an arbitrary up axis.
  457. if (perpindicularDir.y() < _stepHeight + 0.001)
  458. {
  459. btVector3 perpComponent = perpindicularDir * movementLength;
  460. targetPosition += perpComponent;
  461. }
  462. }
  463. }
  464. bool PhysicsCharacter::fixCollision(btCollisionWorld* world)
  465. {
  466. GP_ASSERT(_node);
  467. GP_ASSERT(_ghostObject);
  468. GP_ASSERT(world && world->getDispatcher());
  469. GP_ASSERT(Game::getInstance()->getPhysicsController());
  470. bool collision = false;
  471. btOverlappingPairCache* pairCache = _ghostObject->getOverlappingPairCache();
  472. GP_ASSERT(pairCache);
  473. // Tell the world to dispatch collision events for our ghost object.
  474. world->getDispatcher()->dispatchAllCollisionPairs(pairCache, world->getDispatchInfo(), world->getDispatcher());
  475. // Store our current world position.
  476. Vector3 startPosition;
  477. _node->getWorldMatrix().getTranslation(&startPosition);
  478. btVector3 currentPosition = BV(startPosition);
  479. // Handle all collisions/overlappign pairs.
  480. btScalar maxPenetration = btScalar(0.0);
  481. for (int i = 0, count = pairCache->getNumOverlappingPairs(); i < count; ++i)
  482. {
  483. _manifoldArray.resize(0);
  484. // Query contacts between this overlapping pair (store in _manifoldArray).
  485. btBroadphasePair* collisionPair = &pairCache->getOverlappingPairArray()[i];
  486. if (collisionPair->m_algorithm)
  487. {
  488. collisionPair->m_algorithm->getAllContactManifolds(_manifoldArray);
  489. }
  490. for (int j = 0, manifoldCount = _manifoldArray.size(); j < manifoldCount; ++j)
  491. {
  492. btPersistentManifold* manifold = _manifoldArray[j];
  493. GP_ASSERT(manifold);
  494. // Get the direction of the contact points (used to scale normal vector in the correct direction).
  495. btScalar directionSign = manifold->getBody0() == _ghostObject ? -1.0f : 1.0f;
  496. // Skip ghost objects.
  497. PhysicsCollisionObject* object = Game::getInstance()->getPhysicsController()->getCollisionObject(
  498. (btCollisionObject*)(manifold->getBody0() == _ghostObject ? manifold->getBody1() : manifold->getBody0()));
  499. if (!object || object->getType() == PhysicsCollisionObject::GHOST_OBJECT)
  500. continue;
  501. for (int p = 0, contactCount = manifold->getNumContacts(); p < contactCount; ++p)
  502. {
  503. const btManifoldPoint& pt = manifold->getContactPoint(p);
  504. // Get penetration distance for this contact point.
  505. btScalar dist = pt.getDistance();
  506. if (dist < 0.0)
  507. {
  508. // A negative distance means the objects are overlapping.
  509. if (dist < maxPenetration)
  510. {
  511. // Store collision normal for this point.
  512. maxPenetration = dist;
  513. _collisionNormal = pt.m_normalWorldOnB * directionSign;
  514. }
  515. // Calculate new position for object, which is translated back along the collision normal.
  516. currentPosition += pt.m_normalWorldOnB * directionSign * dist * 0.2f;
  517. collision = true;
  518. }
  519. }
  520. }
  521. }
  522. // Set the new world transformation to apply to fix the collision.
  523. _node->translate(Vector3(currentPosition.x(), currentPosition.y(), currentPosition.z()) - startPosition);
  524. return collision;
  525. }
  526. PhysicsCharacter::ActionInterface::ActionInterface(PhysicsCharacter* character) : character(character)
  527. {
  528. }
  529. void PhysicsCharacter::ActionInterface::updateAction(btCollisionWorld* collisionWorld, btScalar deltaTimeStep)
  530. {
  531. character->updateAction(collisionWorld, deltaTimeStep);
  532. }
  533. void PhysicsCharacter::ActionInterface::debugDraw(btIDebugDraw* debugDrawer)
  534. {
  535. // Not used yet.
  536. }
  537. void PhysicsCharacter::updateAction(btCollisionWorld* collisionWorld, btScalar deltaTimeStep)
  538. {
  539. GP_ASSERT(_ghostObject);
  540. GP_ASSERT(_node);
  541. // First check for existing collisions and attempt to respond/fix them.
  542. // Basically we are trying to move the character so that it does not penetrate
  543. // any other collision objects in the scene. We need to do this to ensure that
  544. // the following steps (movement) start from a clean slate, where the character
  545. // is not colliding with anything. Also, this step handles collision between
  546. // dynamic objects (i.e. objects that moved and now intersect the character).
  547. if (_physicsEnabled)
  548. {
  549. _colliding = false;
  550. int stepCount = 0;
  551. while (fixCollision(collisionWorld))
  552. {
  553. _colliding = true;
  554. if (++stepCount > 4)
  555. {
  556. // Most likely we are wedged between a number of different collision objects.
  557. break;
  558. }
  559. }
  560. }
  561. // Update current and target world positions.
  562. btVector3 startPosition = _ghostObject->getWorldTransform().getOrigin();
  563. _currentPosition = startPosition;
  564. // Process movement in the up direction.
  565. if (_physicsEnabled)
  566. stepUp(collisionWorld, deltaTimeStep);
  567. // Process horizontal movement.
  568. stepForwardAndStrafe(collisionWorld, deltaTimeStep);
  569. // Process movement in the down direction.
  570. if (_physicsEnabled)
  571. stepDown(collisionWorld, deltaTimeStep);
  572. // Set new position.
  573. btVector3 translation = _currentPosition - startPosition;
  574. _node->translate(translation.x(), translation.y(), translation.z());
  575. }
  576. }