BsFPSCamera.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "BsFPSCamera.h"
  2. #include "Math/BsVector3.h"
  3. #include "Math/BsMath.h"
  4. #include "Scene/BsSceneObject.h"
  5. #include "Physics/BsPhysics.h"
  6. namespace bs
  7. {
  8. /** Determines speed of camera rotation. */
  9. constexpr float ROTATION_SPEED = 3.0f;
  10. /** Determines range of movement for pitch rotation, in either direction. */
  11. constexpr Degree PITCH_RANGE = Degree(45.0f);
  12. FPSCamera::FPSCamera(const HSceneObject& parent)
  13. :Component(parent)
  14. {
  15. // Set a name for the component, so we can find it later if needed
  16. setName("FPSCamera");
  17. // Get handles for key bindings. Actual keys attached to these bindings will be registered during app start-up.
  18. mHorizontalAxis = VirtualAxis("Horizontal");
  19. mVerticalAxis = VirtualAxis("Vertical");
  20. // Determine initial yaw and pitch
  21. Quaternion rotation = SO()->getTransform().getRotation();
  22. Radian pitch, yaw, roll;
  23. (void)rotation.toEulerAngles(pitch, yaw, roll);
  24. mPitch = pitch;
  25. mYaw = yaw;
  26. applyAngles();
  27. }
  28. void FPSCamera::update()
  29. {
  30. // If camera is rotating, apply new pitch/yaw rotation values depending on the amount of rotation from the
  31. // vertical/horizontal axes.
  32. mYaw += Degree(gVirtualInput().getAxisValue(mHorizontalAxis) * ROTATION_SPEED);
  33. mPitch += Degree(gVirtualInput().getAxisValue(mVerticalAxis) * ROTATION_SPEED);
  34. applyAngles();
  35. }
  36. void FPSCamera::applyAngles()
  37. {
  38. mYaw.wrap();
  39. mPitch.wrap();
  40. const Degree pitchMax = PITCH_RANGE;
  41. const Degree pitchMin = Degree(360.0f) - PITCH_RANGE;
  42. if(mPitch > pitchMax && mPitch < pitchMin)
  43. {
  44. if((mPitch - pitchMax) > (pitchMin - mPitch))
  45. mPitch = pitchMin;
  46. else
  47. mPitch = pitchMax;
  48. }
  49. Quaternion yRot(Vector3::UNIT_Y, Radian(mYaw));
  50. Quaternion xRot(Vector3::UNIT_X, Radian(mPitch));
  51. if(!mCharacterSO)
  52. {
  53. Quaternion camRot = yRot * xRot;
  54. camRot.normalize();
  55. SO()->setRotation(camRot);
  56. }
  57. else
  58. {
  59. mCharacterSO->setRotation(yRot);
  60. SO()->setRotation(xRot);
  61. }
  62. }
  63. }