FPSCamera.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "FPSCamera.h"
  9. #include "Actor.h"
  10. FPSCamera::FPSCamera(Actor* owner)
  11. :CameraComponent(owner)
  12. ,mPitchSpeed(0.0f)
  13. ,mMaxPitch(Math::Pi / 3.0f)
  14. ,mPitch(0.0f)
  15. {
  16. }
  17. void FPSCamera::Update(float deltaTime)
  18. {
  19. // Call parent update (doesn't do anything right now)
  20. CameraComponent::Update(deltaTime);
  21. // Camera position is owner position
  22. Vector3 cameraPos = mOwner->GetPosition();
  23. // Update pitch based on pitch speed
  24. mPitch += mPitchSpeed * deltaTime;
  25. // Clamp pitch to [-max, +max]
  26. mPitch = Math::Clamp(mPitch, -mMaxPitch, mMaxPitch);
  27. // Make a quaternion representing pitch rotation,
  28. // which is about owner's right vector
  29. Quaternion q(mOwner->GetRight(), mPitch);
  30. // Rotate owner forward by pitch quaternion
  31. Vector3 viewForward = Vector3::Transform(
  32. mOwner->GetForward(), q);
  33. // Target position 100 units in front of view forward
  34. Vector3 target = cameraPos + viewForward * 100.0f;
  35. // Also rotate up by pitch quaternion
  36. Vector3 up = Vector3::Transform(Vector3::UnitZ, q);
  37. // Create look at matrix, set as view
  38. Matrix4 view = Matrix4::CreateLookAt(cameraPos, target, up);
  39. SetViewMatrix(view);
  40. }