ChangeMotionTypeTest.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/General/ChangeMotionTypeTest.h>
  6. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  7. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  8. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  9. #include <Layers.h>
  10. JPH_IMPLEMENT_RTTI_VIRTUAL(ChangeMotionTypeTest)
  11. {
  12. JPH_ADD_BASE_CLASS(ChangeMotionTypeTest, Test)
  13. }
  14. void ChangeMotionTypeTest::Initialize()
  15. {
  16. // Floor
  17. CreateFloor();
  18. // Create body as static, but allow to become dynamic
  19. BodyCreationSettings settings;
  20. settings.SetShape(new BoxShape(Vec3(0.5f, 1.0f, 2.0f)));
  21. settings.mPosition = RVec3(0, 10, 0);
  22. settings.mMotionType = EMotionType::Dynamic;
  23. settings.mObjectLayer = Layers::MOVING; // Put in moving layer, this will result in some overhead when the body is static
  24. settings.mAllowDynamicOrKinematic = true;
  25. mBody = mBodyInterface->CreateBody(settings);
  26. mBodyInterface->AddBody(mBody->GetID(), EActivation::Activate);
  27. }
  28. void ChangeMotionTypeTest::UpdateMotionType()
  29. {
  30. // Calculate desired motion type
  31. static const EMotionType cycle[] = { EMotionType::Dynamic, EMotionType::Kinematic, EMotionType::Static, EMotionType::Kinematic, EMotionType::Dynamic, EMotionType::Static };
  32. EMotionType motion_type = cycle[int(mTime) % size(cycle)];
  33. // Update motion type and reactivate the body
  34. if (motion_type != mBody->GetMotionType())
  35. mBodyInterface->SetMotionType(mBody->GetID(), motion_type, EActivation::Activate);
  36. }
  37. void ChangeMotionTypeTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  38. {
  39. // Increment time
  40. mTime += inParams.mDeltaTime;
  41. UpdateMotionType();
  42. // Provide kinematic body a target
  43. if (mBody->IsKinematic())
  44. mBody->MoveKinematic(RVec3(Sin(mTime), 10, 0), Quat::sRotation(Vec3::sAxisX(), Cos(mTime)), inParams.mDeltaTime);
  45. }
  46. void ChangeMotionTypeTest::SaveState(StateRecorder &inStream) const
  47. {
  48. inStream.Write(mTime);
  49. }
  50. void ChangeMotionTypeTest::RestoreState(StateRecorder &inStream)
  51. {
  52. inStream.Read(mTime);
  53. UpdateMotionType();
  54. }