ChangeMotionTypeTest.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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::Static;
  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. UpdateMotionType();
  28. }
  29. void ChangeMotionTypeTest::UpdateMotionType()
  30. {
  31. static const EMotionType cycle[] = { EMotionType::Dynamic, EMotionType::Kinematic, EMotionType::Static, EMotionType::Kinematic, EMotionType::Dynamic, EMotionType::Static };
  32. static const char *label[] = { "Dynamic", "Kinematic", "Static", "Kinematic", "Dynamic", "Static" };
  33. // Calculate desired motion type
  34. int idx = int(mTime) % size(cycle);
  35. EMotionType motion_type = cycle[idx];
  36. // Update motion type and reactivate the body
  37. if (motion_type != mBody->GetMotionType())
  38. {
  39. mBodyInterface->SetMotionType(mBody->GetID(), motion_type, EActivation::Activate);
  40. SetBodyLabel(mBody->GetID(), label[idx]);
  41. }
  42. }
  43. void ChangeMotionTypeTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  44. {
  45. // Increment time
  46. mTime += inParams.mDeltaTime;
  47. UpdateMotionType();
  48. // Provide kinematic body a target
  49. if (mBody->IsKinematic())
  50. mBody->MoveKinematic(RVec3(Sin(mTime), 10, 0), Quat::sRotation(Vec3::sAxisX(), Cos(mTime)), inParams.mDeltaTime);
  51. }
  52. void ChangeMotionTypeTest::SaveState(StateRecorder &inStream) const
  53. {
  54. inStream.Write(mTime);
  55. }
  56. void ChangeMotionTypeTest::RestoreState(StateRecorder &inStream)
  57. {
  58. inStream.Read(mTime);
  59. UpdateMotionType();
  60. }