PhysicsMotionState.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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(btVector3(centerOfMassOffset->x, centerOfMassOffset->y, centerOfMassOffset->z));
  11. }
  12. updateTransformFromNode();
  13. }
  14. PhysicsMotionState::~PhysicsMotionState()
  15. {
  16. }
  17. void PhysicsMotionState::getWorldTransform(btTransform &transform) const
  18. {
  19. if (_node->getPhysicsRigidBody() && _node->getPhysicsRigidBody()->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. btQuaternion orientation(rotation.x, rotation.y, rotation.z, rotation.w);
  42. btTransform offset = btTransform(orientation, 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(orientation, origin);
  47. }
  48. else
  49. {
  50. _worldTransform = btTransform(btQuaternion(rotation.x, rotation.y, rotation.z, rotation.w), btVector3(m.m[12], m.m[13], m.m[14]));
  51. }
  52. }
  53. }