PhysicsMotionState.cpp 2.2 KB

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