CharacterSpaceShipTest.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Character/CharacterSpaceShipTest.h>
  6. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
  9. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  10. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  11. #include <Layers.h>
  12. JPH_IMPLEMENT_RTTI_VIRTUAL(CharacterSpaceShipTest)
  13. {
  14. JPH_ADD_BASE_CLASS(CharacterSpaceShipTest, Test)
  15. }
  16. void CharacterSpaceShipTest::Initialize()
  17. {
  18. // Dimensions of our space ship
  19. constexpr float cSpaceShipHeight = 2.0f;
  20. constexpr float cSpaceShipRingHeight = 0.2f;
  21. constexpr float cSpaceShipRadius = 100.0f;
  22. const RVec3 cShipInitialPosition(-25, 15, 0);
  23. // Create floor for reference
  24. CreateFloor();
  25. // Create 'player' character
  26. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  27. settings->mShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  28. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  29. mCharacter = new CharacterVirtual(settings, cShipInitialPosition + Vec3(0, cSpaceShipHeight, 0), Quat::sIdentity(), mPhysicsSystem);
  30. mCharacter->SetListener(this);
  31. // Create the space ship
  32. StaticCompoundShapeSettings compound;
  33. compound.SetEmbedded();
  34. for (float h = cSpaceShipRingHeight; h < cSpaceShipHeight; h += cSpaceShipRingHeight)
  35. compound.AddShape(Vec3::sZero(), Quat::sIdentity(), new CylinderShape(h, sqrt(Square(cSpaceShipRadius) - Square(cSpaceShipRadius - cSpaceShipHeight - cSpaceShipRingHeight + h))));
  36. mSpaceShip = mBodyInterface->CreateAndAddBody(BodyCreationSettings(&compound, cShipInitialPosition, Quat::sIdentity(), EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  37. mSpaceShipPrevTransform = mBodyInterface->GetCenterOfMassTransform(mSpaceShip);
  38. }
  39. void CharacterSpaceShipTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  40. {
  41. // Update scene time
  42. mTime += inParams.mDeltaTime;
  43. // Update the character so it stays relative to the space ship
  44. RMat44 new_space_ship_transform = mBodyInterface->GetCenterOfMassTransform(mSpaceShip);
  45. mCharacter->SetPosition(new_space_ship_transform * mSpaceShipPrevTransform.Inversed() * mCharacter->GetPosition());
  46. // Update the character rotation and its up vector to match the new up vector of the ship
  47. mCharacter->SetUp(new_space_ship_transform.GetAxisY());
  48. mCharacter->SetRotation(new_space_ship_transform.GetRotation().GetQuaternion());
  49. // Draw character pre update (the sim is also drawn pre update)
  50. // Note that we have first updated the position so that it matches the new position of the ship
  51. #ifdef JPH_DEBUG_RENDERER
  52. mCharacter->GetShape()->Draw(mDebugRenderer, mCharacter->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f), Color::sGreen, false, true);
  53. #endif // JPH_DEBUG_RENDERER
  54. // Determine controller input
  55. Vec3 control_input = Vec3::sZero();
  56. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT)) control_input.SetZ(-1);
  57. if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT)) control_input.SetZ(1);
  58. if (inParams.mKeyboard->IsKeyPressed(DIK_UP)) control_input.SetX(1);
  59. if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN)) control_input.SetX(-1);
  60. if (control_input != Vec3::sZero())
  61. control_input = control_input.Normalized();
  62. // Calculate the desired velocity in local space to the ship based on the camera forward
  63. Vec3 cam_fwd = new_space_ship_transform.GetRotation().Multiply3x3Transposed(inParams.mCameraState.mForward);
  64. cam_fwd.SetY(0.0f);
  65. cam_fwd = cam_fwd.NormalizedOr(Vec3::sAxisX());
  66. Quat rotation = Quat::sFromTo(Vec3::sAxisX(), cam_fwd);
  67. control_input = rotation * control_input;
  68. // Smooth the player input in local space to the ship
  69. mDesiredVelocity = 0.25f * control_input * cCharacterSpeed + 0.75f * mDesiredVelocity;
  70. // Check jump
  71. bool jump = false;
  72. for (int key = inParams.mKeyboard->GetFirstKey(); key != 0; key = inParams.mKeyboard->GetNextKey())
  73. {
  74. if (key == DIK_RCONTROL)
  75. jump = true;
  76. }
  77. // Determine new character velocity
  78. Vec3 current_vertical_velocity = mCharacter->GetLinearVelocity().Dot(mSpaceShipPrevTransform.GetAxisY()) * mCharacter->GetUp();
  79. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  80. Vec3 new_velocity;
  81. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  82. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  83. {
  84. // Assume velocity of ground when on ground
  85. new_velocity = ground_velocity;
  86. // Jump
  87. if (jump)
  88. new_velocity += cJumpSpeed * mCharacter->GetUp();
  89. }
  90. else
  91. new_velocity = current_vertical_velocity;
  92. // Gravity always acts relative to the ship
  93. Vec3 gravity = new_space_ship_transform.Multiply3x3(mPhysicsSystem->GetGravity());
  94. new_velocity += gravity * inParams.mDeltaTime;
  95. // Transform player input to world space
  96. new_velocity += new_space_ship_transform.Multiply3x3(mDesiredVelocity);
  97. // Update character velocity
  98. mCharacter->SetLinearVelocity(new_velocity);
  99. // Update the character position
  100. CharacterVirtual::ExtendedUpdateSettings update_settings;
  101. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  102. gravity,
  103. update_settings,
  104. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  105. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  106. { },
  107. { },
  108. *mTempAllocator);
  109. // Update previous transform
  110. mSpaceShipPrevTransform = new_space_ship_transform;
  111. // Calculate new velocity
  112. UpdateShipVelocity();
  113. }
  114. void CharacterSpaceShipTest::UpdateShipVelocity()
  115. {
  116. // Make it a rocky ride...
  117. mSpaceShipLinearVelocity = Vec3(Sin(mTime), 0, Cos(mTime)) * 50.0f;
  118. mSpaceShipAngularVelocity = Vec3(Sin(2.0f * mTime), 1, Cos(2.0f * mTime)) * 0.5f;
  119. mBodyInterface->SetLinearAndAngularVelocity(mSpaceShip, mSpaceShipLinearVelocity, mSpaceShipAngularVelocity);
  120. }
  121. void CharacterSpaceShipTest::GetInitialCamera(CameraState& ioState) const
  122. {
  123. // This will become the local space offset, look down the x axis and slightly down
  124. ioState.mPos = RVec3::sZero();
  125. ioState.mForward = Vec3(10.0f, -2.0f, 0).Normalized();
  126. }
  127. RMat44 CharacterSpaceShipTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  128. {
  129. // Pivot is center of character + distance behind based on the heading and pitch of the camera
  130. Vec3 fwd = Vec3(Cos(inCameraPitch) * Cos(inCameraHeading), Sin(inCameraPitch), Cos(inCameraPitch) * Sin(inCameraHeading));
  131. return RMat44::sTranslation(mCharacter->GetPosition() + Vec3(0, cCharacterHeightStanding + cCharacterRadiusStanding, 0) - 5.0f * fwd);
  132. }
  133. void CharacterSpaceShipTest::SaveState(StateRecorder &inStream) const
  134. {
  135. mCharacter->SaveState(inStream);
  136. inStream.Write(mTime);
  137. inStream.Write(mDesiredVelocity);
  138. inStream.Write(mSpaceShipPrevTransform);
  139. }
  140. void CharacterSpaceShipTest::RestoreState(StateRecorder &inStream)
  141. {
  142. mCharacter->RestoreState(inStream);
  143. inStream.Read(mTime);
  144. inStream.Read(mDesiredVelocity);
  145. inStream.Read(mSpaceShipPrevTransform);
  146. // Calculate new velocity
  147. UpdateShipVelocity();
  148. }
  149. void CharacterSpaceShipTest::OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity)
  150. {
  151. // Cancel out velocity of space ship, we move relative to this which means we don't feel any of the acceleration of the ship (= engage inertial dampeners!)
  152. ioLinearVelocity -= mSpaceShipLinearVelocity;
  153. ioAngularVelocity -= mSpaceShipAngularVelocity;
  154. }