OrbitCamera.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 "OrbitCamera.h"
  9. #include "Actor.h"
  10. OrbitCamera::OrbitCamera(Actor* owner)
  11. :CameraComponent(owner)
  12. ,mOffset(-400.0f, 0.0f, 0.0f)
  13. ,mUp(Vector3::UnitZ)
  14. ,mPitchSpeed(0.0f)
  15. ,mYawSpeed(0.0f)
  16. {
  17. }
  18. void OrbitCamera::Update(float deltaTime)
  19. {
  20. CameraComponent::Update(deltaTime);
  21. // Create a quaternion for yaw about world up
  22. Quaternion yaw(Vector3::UnitZ, mYawSpeed * deltaTime);
  23. // Transform offset and up by yaw
  24. mOffset = Vector3::Transform(mOffset, yaw);
  25. mUp = Vector3::Transform(mUp, yaw);
  26. // Compute camera forward/right from these vectors
  27. // Forward owner.position - (owner.position + offset)
  28. // = -offset
  29. Vector3 forward = -1.0f * mOffset;
  30. forward.Normalize();
  31. Vector3 right = Vector3::Cross(mUp, forward);
  32. right.Normalize();
  33. // Create quaternion for pitch about camera right
  34. Quaternion pitch(right, mPitchSpeed * deltaTime);
  35. // Transform camera offset and up by pitch
  36. mOffset = Vector3::Transform(mOffset, pitch);
  37. mUp = Vector3::Transform(mUp, pitch);
  38. // Compute transform matrix
  39. Vector3 target = mOwner->GetPosition();
  40. Vector3 cameraPos = target + mOffset;
  41. Matrix4 view = Matrix4::CreateLookAt(cameraPos, target, mUp);
  42. SetViewMatrix(view);
  43. }