PhysicsMotionState.cpp 2.2 KB

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