2
0

PhysicsCharacter.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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, int group, int mask)
  44. : PhysicsGhostObject(node, shape, group, mask), _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.isEmpty())
  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. return character;
  122. }
  123. PhysicsCollisionObject::Type PhysicsCharacter::getType() const
  124. {
  125. return PhysicsCollisionObject::CHARACTER;
  126. }
  127. btCollisionObject* PhysicsCharacter::getCollisionObject() const
  128. {
  129. return _ghostObject;
  130. }
  131. bool PhysicsCharacter::isPhysicsEnabled() const
  132. {
  133. return _physicsEnabled;
  134. }
  135. void PhysicsCharacter::setPhysicsEnabled(bool enabled)
  136. {
  137. _physicsEnabled = enabled;
  138. }
  139. float PhysicsCharacter::getMaxStepHeight() const
  140. {
  141. return _stepHeight;
  142. }
  143. void PhysicsCharacter::setMaxStepHeight(float height)
  144. {
  145. _stepHeight = height;
  146. }
  147. float PhysicsCharacter::getMaxSlopeAngle() const
  148. {
  149. return _slopeAngle;
  150. }
  151. void PhysicsCharacter::setMaxSlopeAngle(float angle)
  152. {
  153. _slopeAngle = angle;
  154. _cosSlopeAngle = std::cos(MATH_DEG_TO_RAD(angle));
  155. }
  156. void PhysicsCharacter::setVelocity(const Vector3& velocity)
  157. {
  158. _moveVelocity.setValue(velocity.x, velocity.y, velocity.z);
  159. }
  160. void PhysicsCharacter::setVelocity(float x, float y, float z)
  161. {
  162. _moveVelocity.setValue(x, y, z);
  163. }
  164. void PhysicsCharacter::rotate(const Vector3& axis, float angle)
  165. {
  166. GP_ASSERT(_node);
  167. _node->rotate(axis, angle);
  168. }
  169. void PhysicsCharacter::rotate(const Quaternion& rotation)
  170. {
  171. GP_ASSERT(_node);
  172. _node->rotate(rotation);
  173. }
  174. void PhysicsCharacter::setRotation(const Vector3& axis, float angle)
  175. {
  176. GP_ASSERT(_node);
  177. _node->setRotation(axis, angle);
  178. }
  179. void PhysicsCharacter::setRotation(const Quaternion& rotation)
  180. {
  181. GP_ASSERT(_node);
  182. _node->setRotation(rotation);
  183. }
  184. void PhysicsCharacter::setForwardVelocity(float velocity)
  185. {
  186. _forwardVelocity = velocity;
  187. }
  188. void PhysicsCharacter::setRightVelocity(float velocity)
  189. {
  190. _rightVelocity = velocity;
  191. }
  192. Vector3 PhysicsCharacter::getCurrentVelocity() const
  193. {
  194. Vector3 v(_currentVelocity.x(), _currentVelocity.y(), _currentVelocity.z());
  195. v.x += _verticalVelocity.x();
  196. v.y += _verticalVelocity.y();
  197. v.z += _verticalVelocity.z();
  198. return v;
  199. }
  200. void PhysicsCharacter::jump(float height)
  201. {
  202. // TODO: Add support for different jump modes (i.e. double jump, changing direction in air, holding down jump button for extra height, etc)
  203. if (!_verticalVelocity.isZero())
  204. return;
  205. // v = sqrt(v0^2 + 2 a s)
  206. // v0 == initial velocity (zero for jumping)
  207. // a == acceleration (inverse gravity)
  208. // s == linear displacement (height)
  209. GP_ASSERT(Game::getInstance()->getPhysicsController());
  210. Vector3 jumpVelocity = -Game::getInstance()->getPhysicsController()->getGravity() * height * 2.0f;
  211. jumpVelocity.set(
  212. jumpVelocity.x == 0 ? 0 : std::sqrt(jumpVelocity.x),
  213. jumpVelocity.y == 0 ? 0 : std::sqrt(jumpVelocity.y),
  214. jumpVelocity.z == 0 ? 0 : std::sqrt(jumpVelocity.z));
  215. _verticalVelocity += BV(jumpVelocity);
  216. }
  217. void PhysicsCharacter::updateCurrentVelocity()
  218. {
  219. GP_ASSERT(_node);
  220. Vector3 temp;
  221. btScalar velocity2 = 0;
  222. // Reset velocity vector.
  223. _normalizedVelocity.setValue(0, 0, 0);
  224. // Add movement velocity contribution.
  225. if (!_moveVelocity.isZero())
  226. {
  227. _normalizedVelocity = _moveVelocity;
  228. velocity2 = _moveVelocity.length2();
  229. }
  230. // Add forward velocity contribution.
  231. if (_forwardVelocity != 0)
  232. {
  233. _node->getWorldMatrix().getForwardVector(&temp);
  234. temp.normalize();
  235. temp *= -_forwardVelocity;
  236. _normalizedVelocity += btVector3(temp.x, temp.y, temp.z);
  237. velocity2 = std::max(std::fabs(velocity2), std::fabs(_forwardVelocity*_forwardVelocity));
  238. }
  239. // Add right velocity contribution.
  240. if (_rightVelocity != 0)
  241. {
  242. _node->getWorldMatrix().getRightVector(&temp);
  243. temp.normalize();
  244. temp *= _rightVelocity;
  245. _normalizedVelocity += btVector3(temp.x, temp.y, temp.z);
  246. velocity2 = std::max(std::fabs(velocity2), std::fabs(_rightVelocity*_rightVelocity));
  247. }
  248. // Compute final combined movement vectors
  249. if (_normalizedVelocity.isZero())
  250. {
  251. _currentVelocity.setZero();
  252. }
  253. else
  254. {
  255. _normalizedVelocity.normalize();
  256. _currentVelocity = _normalizedVelocity * std::sqrt(velocity2);
  257. }
  258. }
  259. void PhysicsCharacter::stepUp(btCollisionWorld* collisionWorld, btScalar time)
  260. {
  261. btVector3 targetPosition(_currentPosition);
  262. if (_verticalVelocity.isZero())
  263. {
  264. // Simply increase our position by step height to enable us
  265. // to smoothly move over steps.
  266. targetPosition += btVector3(0, _stepHeight, 0);
  267. }
  268. // TODO: Convex sweep test to ensure we didn't hit anything during the step up.
  269. _currentPosition = targetPosition;
  270. }
  271. void PhysicsCharacter::stepForwardAndStrafe(btCollisionWorld* collisionWorld, float time)
  272. {
  273. updateCurrentVelocity();
  274. // Calculate final velocity
  275. btVector3 velocity(_currentVelocity);
  276. velocity *= time; // since velocity is in meters per second
  277. if (velocity.isZero())
  278. {
  279. // No velocity, so we aren't moving
  280. return;
  281. }
  282. // Translate the target position by the velocity vector (already scaled by t)
  283. btVector3 targetPosition = _currentPosition + velocity;
  284. // If physics is disabled, simply update current position without checking collisions
  285. if (!_physicsEnabled)
  286. {
  287. _currentPosition = targetPosition;
  288. return;
  289. }
  290. // Check for collisions by performing a bullet convex sweep test
  291. btTransform start;
  292. btTransform end;
  293. start.setIdentity();
  294. end.setIdentity();
  295. btScalar fraction = 1.0;
  296. btScalar distance2;
  297. if (_colliding && (_normalizedVelocity.dot(_collisionNormal) > btScalar(0.0)))
  298. {
  299. updateTargetPositionFromCollision(targetPosition, _collisionNormal);
  300. }
  301. int maxIter = 10;
  302. GP_ASSERT(_ghostObject && _ghostObject->getBroadphaseHandle());
  303. GP_ASSERT(_collisionShape);
  304. GP_ASSERT(collisionWorld);
  305. GP_ASSERT(Game::getInstance()->getPhysicsController());
  306. while (fraction > btScalar(0.01) && maxIter-- > 0)
  307. {
  308. start.setOrigin(_currentPosition);
  309. end.setOrigin(targetPosition);
  310. btVector3 sweepDirNegative(_currentPosition - targetPosition);
  311. ClosestNotMeConvexResultCallback callback(this, sweepDirNegative, btScalar(0.0));
  312. callback.m_collisionFilterGroup = _ghostObject->getBroadphaseHandle()->m_collisionFilterGroup;
  313. callback.m_collisionFilterMask = _ghostObject->getBroadphaseHandle()->m_collisionFilterMask;
  314. _ghostObject->convexSweepTest(static_cast<btConvexShape*>(_collisionShape->getShape()), start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  315. fraction -= callback.m_closestHitFraction;
  316. if (callback.hasHit())
  317. {
  318. Vector3 normal(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  319. PhysicsCollisionObject* o = Game::getInstance()->getPhysicsController()->getCollisionObject(callback.m_hitCollisionObject);
  320. GP_ASSERT(o);
  321. if (o->getType() == PhysicsCollisionObject::RIGID_BODY && o->isDynamic())
  322. {
  323. PhysicsRigidBody* rb = static_cast<PhysicsRigidBody*>(o);
  324. GP_ASSERT(rb);
  325. normal.normalize();
  326. rb->applyImpulse(_mass * -normal * velocity.length());
  327. }
  328. updateTargetPositionFromCollision(targetPosition, callback.m_hitNormalWorld);
  329. btVector3 currentDir = targetPosition - _currentPosition;
  330. distance2 = currentDir.length2();
  331. if (distance2 > FLT_EPSILON)
  332. {
  333. currentDir.normalize();
  334. // If velocity is against original velocity, stop to avoid tiny oscilations in sloping corners.
  335. if (currentDir.dot(_normalizedVelocity) <= btScalar(0.0))
  336. {
  337. break;
  338. }
  339. }
  340. }
  341. else
  342. {
  343. // Nothing in our way
  344. break;
  345. }
  346. }
  347. _currentPosition = targetPosition;
  348. }
  349. void PhysicsCharacter::stepDown(btCollisionWorld* collisionWorld, btScalar time)
  350. {
  351. GP_ASSERT(Game::getInstance()->getPhysicsController() && Game::getInstance()->getPhysicsController()->_world);
  352. GP_ASSERT(_ghostObject && _ghostObject->getBroadphaseHandle());
  353. GP_ASSERT(_collisionShape);
  354. GP_ASSERT(collisionWorld);
  355. // Contribute gravity to vertical velocity.
  356. btVector3 gravity = Game::getInstance()->getPhysicsController()->_world->getGravity();
  357. _verticalVelocity += (gravity * time);
  358. // Compute new position from vertical velocity.
  359. btVector3 targetPosition = _currentPosition + (_verticalVelocity * time);
  360. targetPosition -= btVector3(0, _stepHeight, 0);
  361. // Perform a convex sweep test between current and target position.
  362. btTransform start;
  363. btTransform end;
  364. start.setIdentity();
  365. end.setIdentity();
  366. btScalar fraction = 1.0;
  367. int maxIter = 10;
  368. while (fraction > btScalar(0.01) && maxIter-- > 0)
  369. {
  370. start.setOrigin(_currentPosition);
  371. end.setOrigin(targetPosition);
  372. btVector3 sweepDirNegative(_currentPosition - targetPosition);
  373. ClosestNotMeConvexResultCallback callback(this, sweepDirNegative, 0.0);
  374. callback.m_collisionFilterGroup = _ghostObject->getBroadphaseHandle()->m_collisionFilterGroup;
  375. callback.m_collisionFilterMask = _ghostObject->getBroadphaseHandle()->m_collisionFilterMask;
  376. _ghostObject->convexSweepTest(static_cast<btConvexShape*>(_collisionShape->getShape()), start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  377. fraction -= callback.m_closestHitFraction;
  378. if (callback.hasHit())
  379. {
  380. // Collision detected, fix it.
  381. Vector3 normal(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  382. normal.normalize();
  383. float dot = normal.dot(Vector3::unitY());
  384. if (dot > 1.0f - MATH_EPSILON)
  385. {
  386. targetPosition.setInterpolate3(_currentPosition, targetPosition, callback.m_closestHitFraction);
  387. // Zero out fall velocity when we hit an object going straight down.
  388. _verticalVelocity.setZero();
  389. break;
  390. }
  391. else
  392. {
  393. PhysicsCollisionObject* o = Game::getInstance()->getPhysicsController()->getCollisionObject(callback.m_hitCollisionObject);
  394. GP_ASSERT(o);
  395. if (o->getType() == PhysicsCollisionObject::RIGID_BODY && o->isDynamic())
  396. {
  397. PhysicsRigidBody* rb = static_cast<PhysicsRigidBody*>(o);
  398. GP_ASSERT(rb);
  399. normal.normalize();
  400. rb->applyImpulse(_mass * -normal * sqrt(BV(normal).dot(_verticalVelocity)));
  401. }
  402. updateTargetPositionFromCollision(targetPosition, BV(normal));
  403. }
  404. }
  405. else
  406. {
  407. // Nothing is in the way.
  408. break;
  409. }
  410. }
  411. // Calculate what the vertical velocity actually is.
  412. // In cases where the character might not actually be able to move down,
  413. // but isn't intersecting with an object straight down either, we don't
  414. // want to keep increasing the vertical velocity until the character
  415. // randomly drops through the floor when it can finally move due to its
  416. // vertical velocity having such a great magnitude.
  417. if (!_verticalVelocity.isZero() && time > 0.0f)
  418. _verticalVelocity = ((targetPosition + btVector3(0.0, _stepHeight, 0.0)) - _currentPosition) / time;
  419. _currentPosition = targetPosition;
  420. }
  421. /*
  422. * Returns the reflection direction of a ray going 'direction' hitting a surface with normal 'normal'.
  423. */
  424. static btVector3 computeReflectionDirection(const btVector3& direction, const btVector3& normal)
  425. {
  426. return direction - (btScalar(2.0) * direction.dot(normal)) * normal;
  427. }
  428. /*
  429. * Returns the portion of 'direction' that is parallel to 'normal'.
  430. */
  431. static btVector3 parallelComponent(const btVector3& direction, const btVector3& normal)
  432. {
  433. btScalar magnitude = direction.dot(normal);
  434. return normal * magnitude;
  435. }
  436. /*
  437. * Returns the portion of 'direction' that is perpendicular to 'normal'.
  438. */
  439. static btVector3 perpindicularComponent(const btVector3& direction, const btVector3& normal)
  440. {
  441. return direction - parallelComponent(direction, normal);
  442. }
  443. void PhysicsCharacter::updateTargetPositionFromCollision(btVector3& targetPosition, const btVector3& collisionNormal)
  444. {
  445. btVector3 movementDirection = targetPosition - _currentPosition;
  446. btScalar movementLength = movementDirection.length();
  447. if (movementLength > FLT_EPSILON)
  448. {
  449. movementDirection.normalize();
  450. btVector3 reflectDir = computeReflectionDirection(movementDirection, collisionNormal);
  451. reflectDir.normalize();
  452. btVector3 perpindicularDir = perpindicularComponent(reflectDir, collisionNormal);
  453. targetPosition = _currentPosition;
  454. // Disallow the character from moving up during collision recovery (using an arbitrary reasonable epsilon).
  455. // Note that this will need to be generalized to allow for an arbitrary up axis.
  456. if (perpindicularDir.y() < _stepHeight + 0.001)
  457. {
  458. btVector3 perpComponent = perpindicularDir * movementLength;
  459. targetPosition += perpComponent;
  460. }
  461. }
  462. }
  463. bool PhysicsCharacter::fixCollision(btCollisionWorld* world)
  464. {
  465. GP_ASSERT(_node);
  466. GP_ASSERT(_ghostObject);
  467. GP_ASSERT(world && world->getDispatcher());
  468. GP_ASSERT(Game::getInstance()->getPhysicsController());
  469. bool collision = false;
  470. btOverlappingPairCache* pairCache = _ghostObject->getOverlappingPairCache();
  471. GP_ASSERT(pairCache);
  472. // Tell the world to dispatch collision events for our ghost object.
  473. world->getDispatcher()->dispatchAllCollisionPairs(pairCache, world->getDispatchInfo(), world->getDispatcher());
  474. // Store our current world position.
  475. Vector3 startPosition;
  476. _node->getWorldMatrix().getTranslation(&startPosition);
  477. btVector3 currentPosition = BV(startPosition);
  478. // Handle all collisions/overlapping pairs.
  479. btScalar maxPenetration = btScalar(0.0);
  480. for (int i = 0, count = pairCache->getNumOverlappingPairs(); i < count; ++i)
  481. {
  482. _manifoldArray.resize(0);
  483. // Query contacts between this overlapping pair (store in _manifoldArray).
  484. btBroadphasePair* collisionPair = &pairCache->getOverlappingPairArray()[i];
  485. if (collisionPair->m_algorithm)
  486. {
  487. collisionPair->m_algorithm->getAllContactManifolds(_manifoldArray);
  488. }
  489. for (int j = 0, manifoldCount = _manifoldArray.size(); j < manifoldCount; ++j)
  490. {
  491. btPersistentManifold* manifold = _manifoldArray[j];
  492. GP_ASSERT(manifold);
  493. // Get the direction of the contact points (used to scale normal vector in the correct direction).
  494. btScalar directionSign = manifold->getBody0() == _ghostObject ? -1.0f : 1.0f;
  495. // Skip ghost objects.
  496. PhysicsCollisionObject* object = Game::getInstance()->getPhysicsController()->getCollisionObject(
  497. (btCollisionObject*)(manifold->getBody0() == _ghostObject ? manifold->getBody1() : manifold->getBody0()));
  498. if (!object || object->getType() == PhysicsCollisionObject::GHOST_OBJECT)
  499. continue;
  500. for (int p = 0, contactCount = manifold->getNumContacts(); p < contactCount; ++p)
  501. {
  502. const btManifoldPoint& pt = manifold->getContactPoint(p);
  503. // Get penetration distance for this contact point.
  504. btScalar dist = pt.getDistance();
  505. if (dist < 0.0)
  506. {
  507. // A negative distance means the objects are overlapping.
  508. if (dist < maxPenetration)
  509. {
  510. // Store collision normal for this point.
  511. maxPenetration = dist;
  512. _collisionNormal = pt.m_normalWorldOnB * directionSign;
  513. }
  514. // Calculate new position for object, which is translated back along the collision normal.
  515. currentPosition += pt.m_normalWorldOnB * directionSign * dist * 0.2f;
  516. collision = true;
  517. }
  518. }
  519. }
  520. }
  521. // Set the new world transformation to apply to fix the collision.
  522. Vector3 newPosition = Vector3(currentPosition.x(), currentPosition.y(), currentPosition.z()) - startPosition;
  523. if (newPosition != Vector3::zero())
  524. _node->translate(newPosition);
  525. return collision;
  526. }
  527. PhysicsCharacter::ActionInterface::ActionInterface(PhysicsCharacter* character) : character(character)
  528. {
  529. }
  530. void PhysicsCharacter::ActionInterface::updateAction(btCollisionWorld* collisionWorld, btScalar deltaTimeStep)
  531. {
  532. character->updateAction(collisionWorld, deltaTimeStep);
  533. }
  534. void PhysicsCharacter::ActionInterface::debugDraw(btIDebugDraw* debugDrawer)
  535. {
  536. // Not used yet.
  537. }
  538. void PhysicsCharacter::updateAction(btCollisionWorld* collisionWorld, btScalar deltaTimeStep)
  539. {
  540. GP_ASSERT(_ghostObject);
  541. GP_ASSERT(_node);
  542. // First check for existing collisions and attempt to respond/fix them.
  543. // Basically we are trying to move the character so that it does not penetrate
  544. // any other collision objects in the scene. We need to do this to ensure that
  545. // the following steps (movement) start from a clean slate, where the character
  546. // is not colliding with anything. Also, this step handles collision between
  547. // dynamic objects (i.e. objects that moved and now intersect the character).
  548. if (_physicsEnabled)
  549. {
  550. _colliding = false;
  551. int stepCount = 0;
  552. while (fixCollision(collisionWorld))
  553. {
  554. _colliding = true;
  555. if (++stepCount > 4)
  556. {
  557. // Most likely we are wedged between a number of different collision objects.
  558. break;
  559. }
  560. }
  561. }
  562. // Update current and target world positions.
  563. btVector3 startPosition = _ghostObject->getWorldTransform().getOrigin();
  564. _currentPosition = startPosition;
  565. // Process movement in the up direction.
  566. if (_physicsEnabled)
  567. stepUp(collisionWorld, deltaTimeStep);
  568. // Process horizontal movement.
  569. stepForwardAndStrafe(collisionWorld, deltaTimeStep);
  570. // Process movement in the down direction.
  571. if (_physicsEnabled)
  572. stepDown(collisionWorld, deltaTimeStep);
  573. // Set new position.
  574. btVector3 newPosition = _currentPosition - startPosition;
  575. Vector3 translation = Vector3(newPosition.x(), newPosition.y(), newPosition.z());
  576. if (translation != Vector3::zero())
  577. _node->translate(translation);
  578. }
  579. }