PhysicsMotionState.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. GP_ASSERT(_node);
  22. if (_node->getCollisionObject() && _node->getCollisionObject()->isKinematic())
  23. updateTransformFromNode();
  24. transform = _centerOfMassOffset.inverse() * _worldTransform;
  25. }
  26. void PhysicsMotionState::setWorldTransform(const btTransform &transform)
  27. {
  28. GP_ASSERT(_node);
  29. _worldTransform = transform * _centerOfMassOffset;
  30. const btQuaternion& rot = _worldTransform.getRotation();
  31. const btVector3& pos = _worldTransform.getOrigin();
  32. _node->setRotation(rot.x(), rot.y(), rot.z(), rot.w());
  33. _node->setTranslation(pos.x(), pos.y(), pos.z());
  34. }
  35. void PhysicsMotionState::updateTransformFromNode() const
  36. {
  37. GP_ASSERT(_node);
  38. // Store the initial world transform (minus the scale) for use by Bullet later on.
  39. Quaternion rotation;
  40. const Matrix& m = _node->getWorldMatrix();
  41. m.getRotation(&rotation);
  42. if (!_centerOfMassOffset.getOrigin().isZero())
  43. {
  44. // When there is a center of mass offset, we modify the initial world transformation
  45. // so that when physics is initially applied, the object is in the correct location.
  46. btTransform offset = btTransform(BQ(rotation), btVector3(0.0f, 0.0f, 0.0f)) * _centerOfMassOffset.inverse();
  47. btVector3 origin(m.m[12] + _centerOfMassOffset.getOrigin().getX() + offset.getOrigin().getX(),
  48. m.m[13] + _centerOfMassOffset.getOrigin().getY() + offset.getOrigin().getY(),
  49. m.m[14] + _centerOfMassOffset.getOrigin().getZ() + offset.getOrigin().getZ());
  50. _worldTransform = btTransform(BQ(rotation), origin);
  51. }
  52. else
  53. {
  54. _worldTransform = btTransform(BQ(rotation), btVector3(m.m[12], m.m[13], m.m[14]));
  55. }
  56. }
  57. }