FollowCamera.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 "FollowCamera.h"
  9. #include "Actor.h"
  10. FollowCamera::FollowCamera(Actor* owner)
  11. :CameraComponent(owner)
  12. ,mHorzDist(350.0f)
  13. ,mVertDist(150.0f)
  14. ,mTargetDist(100.0f)
  15. ,mSpringConstant(64.0f)
  16. {
  17. }
  18. void FollowCamera::Update(float deltaTime)
  19. {
  20. CameraComponent::Update(deltaTime);
  21. // Compute dampening from spring constant
  22. float dampening = 2.0f * Math::Sqrt(mSpringConstant);
  23. // Compute ideal position
  24. Vector3 idealPos = ComputeCameraPos();
  25. // Compute difference between actual and ideal
  26. Vector3 diff = mActualPos - idealPos;
  27. // Compute acceleration of spring
  28. Vector3 acel = -mSpringConstant * diff -
  29. dampening * mVelocity;
  30. // Update velocity
  31. mVelocity += acel * deltaTime;
  32. // Update actual camera position
  33. mActualPos += mVelocity * deltaTime;
  34. // Target is target dist in front of owning actor
  35. Vector3 target = mOwner->GetPosition() +
  36. mOwner->GetForward() * mTargetDist;
  37. // Use actual position here, not ideal
  38. Matrix4 view = Matrix4::CreateLookAt(mActualPos, target,
  39. Vector3::UnitZ);
  40. SetViewMatrix(view);
  41. }
  42. void FollowCamera::SnapToIdeal()
  43. {
  44. // Set actual position to ideal
  45. mActualPos = ComputeCameraPos();
  46. // Zero velocity
  47. mVelocity = Vector3::Zero;
  48. // Compute target and view
  49. Vector3 target = mOwner->GetPosition() +
  50. mOwner->GetForward() * mTargetDist;
  51. // Use actual position here, not ideal
  52. Matrix4 view = Matrix4::CreateLookAt(mActualPos, target,
  53. Vector3::UnitZ);
  54. SetViewMatrix(view);
  55. }
  56. Vector3 FollowCamera::ComputeCameraPos() const
  57. {
  58. // Set camera position behind and above owner
  59. Vector3 cameraPos = mOwner->GetPosition();
  60. cameraPos -= mOwner->GetForward() * mHorzDist;
  61. cameraPos += Vector3::UnitZ * mVertDist;
  62. return cameraPos;
  63. }