PhysicsMotionState.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "Base.h"
  2. #include "PhysicsMotionState.h"
  3. #include "Node.h"
  4. namespace gameplay
  5. {
  6. PhysicsMotionState::PhysicsMotionState(Node* node, const Vector3* centerOfMassOffset) : _node(node),
  7. _centerOfMassOffset(btTransform::getIdentity())
  8. {
  9. if (centerOfMassOffset)
  10. {
  11. // Store the center of mass offset.
  12. _centerOfMassOffset.setOrigin(BV(*centerOfMassOffset));
  13. }
  14. updateTransformFromNode();
  15. }
  16. PhysicsMotionState::~PhysicsMotionState()
  17. {
  18. }
  19. void PhysicsMotionState::getWorldTransform(btTransform &transform) const
  20. {
  21. if (_node->getCollisionObject() && _node->getCollisionObject()->isKinematic())
  22. updateTransformFromNode();
  23. transform = _centerOfMassOffset.inverse() * _worldTransform;
  24. }
  25. void PhysicsMotionState::setWorldTransform(const btTransform &transform)
  26. {
  27. _worldTransform = transform * _centerOfMassOffset;
  28. const btQuaternion& rot = _worldTransform.getRotation();
  29. const btVector3& pos = _worldTransform.getOrigin();
  30. _node->setRotation(rot.x(), rot.y(), rot.z(), rot.w());
  31. _node->setTranslation(pos.x(), pos.y(), pos.z());
  32. }
  33. void PhysicsMotionState::updateTransformFromNode() const
  34. {
  35. // Store the initial world transform (minus the scale) for use by Bullet later on.
  36. Quaternion rotation;
  37. const Matrix& m = _node->getWorldMatrix();
  38. m.getRotation(&rotation);
  39. if (!_centerOfMassOffset.getOrigin().isZero())
  40. {
  41. // When there is a center of mass offset, we modify the initial world transformation
  42. // so that when physics is initially applied, the object is in the correct location.
  43. btTransform offset = btTransform(BQ(rotation), btVector3(0.0f, 0.0f, 0.0f)) * _centerOfMassOffset.inverse();
  44. btVector3 origin(m.m[12] + _centerOfMassOffset.getOrigin().getX() + offset.getOrigin().getX(),
  45. m.m[13] + _centerOfMassOffset.getOrigin().getY() + offset.getOrigin().getY(),
  46. m.m[14] + _centerOfMassOffset.getOrigin().getZ() + offset.getOrigin().getZ());
  47. _worldTransform = btTransform(BQ(rotation), origin);
  48. }
  49. else
  50. {
  51. _worldTransform = btTransform(BQ(rotation), btVector3(m.m[12], m.m[13], m.m[14]));
  52. }
  53. }
  54. }