CharacterTest.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Character/CharacterTest.h>
  5. #include <Layers.h>
  6. #include <Renderer/DebugRendererImp.h>
  7. JPH_IMPLEMENT_RTTI_VIRTUAL(CharacterTest)
  8. {
  9. JPH_ADD_BASE_CLASS(CharacterTest, CharacterBaseTest)
  10. }
  11. static const float cCollisionTolerance = 0.05f;
  12. CharacterTest::~CharacterTest()
  13. {
  14. mCharacter->RemoveFromPhysicsSystem();
  15. }
  16. void CharacterTest::Initialize()
  17. {
  18. CharacterBaseTest::Initialize();
  19. // Create 'player' character
  20. Ref<CharacterSettings> settings = new CharacterSettings();
  21. settings->mMaxSlopeAngle = DegreesToRadians(45.0f);
  22. settings->mLayer = Layers::MOVING;
  23. settings->mShape = mStandingShape;
  24. settings->mFriction = 0.5f;
  25. mCharacter = new Character(settings, Vec3::sZero(), Quat::sIdentity(), 0, mPhysicsSystem);
  26. mCharacter->AddToPhysicsSystem(EActivation::Activate);
  27. }
  28. void CharacterTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  29. {
  30. CharacterBaseTest::PrePhysicsUpdate(inParams);
  31. // Draw state of character
  32. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), mCharacter->GetLinearVelocity());
  33. }
  34. void CharacterTest::PostPhysicsUpdate(float inDeltaTime)
  35. {
  36. // Fetch the new ground properties
  37. mCharacter->PostSimulation(cCollisionTolerance);
  38. }
  39. void CharacterTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  40. {
  41. // Cancel movement in opposite direction of normal when sliding
  42. Character::EGroundState ground_state = mCharacter->GetGroundState();
  43. if (ground_state == Character::EGroundState::Sliding)
  44. {
  45. Vec3 normal = mCharacter->GetGroundNormal();
  46. normal.SetY(0.0f);
  47. float dot = normal.Dot(inMovementDirection);
  48. if (dot < 0.0f)
  49. inMovementDirection -= (dot * normal) / normal.LengthSq();
  50. }
  51. // Update velocity
  52. Vec3 current_velocity = mCharacter->GetLinearVelocity();
  53. Vec3 desired_velocity = cCharacterSpeed * inMovementDirection;
  54. desired_velocity.SetY(current_velocity.GetY());
  55. Vec3 new_velocity = 0.75f * current_velocity + 0.25f * desired_velocity;
  56. // Stance switch
  57. if (inSwitchStance)
  58. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop);
  59. // Jump
  60. if (inJump && ground_state == Character::EGroundState::OnGround)
  61. new_velocity += Vec3(0, cJumpSpeed, 0);
  62. // Update the velocity
  63. mCharacter->SetLinearVelocity(new_velocity);
  64. }