PhysicsCharacter.cpp 22 KB

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