ObjectRotator.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "ObjectRotator.h"
  4. #include "Math/BsVector3.h"
  5. #include "Utility/BsTime.h"
  6. #include "Math/BsMath.h"
  7. #include "Scene/BsSceneObject.h"
  8. #include "Platform/BsCursor.h"
  9. namespace bs
  10. {
  11. const float ObjectRotator::ROTATION_SPEED = 120.0f; // Degrees/second
  12. /** Wraps an angle so it always stays in [0, 360) range. */
  13. Degree wrapAngle2(Degree angle)
  14. {
  15. if (angle.valueDegrees() < -360.0f)
  16. angle += Degree(360.0f);
  17. if (angle.valueDegrees() > 360.0f)
  18. angle -= Degree(360.0f);
  19. return angle;
  20. }
  21. ObjectRotator::ObjectRotator(const HSceneObject& parent)
  22. :Component(parent), mPitch(0.0f), mYaw(0.0f), mLastButtonState(false)
  23. {
  24. // Set a name for the component, so we can find it later if needed
  25. setName("ObjectRotator");
  26. // Get handles for key bindings. Actual keys attached to these bindings will be registered during app start-up.
  27. mRotateObj = VirtualButton("RotateObj");
  28. mHorizontalAxis = VirtualAxis("Horizontal");
  29. mVerticalAxis = VirtualAxis("Vertical");
  30. }
  31. void ObjectRotator::update()
  32. {
  33. // Check if any movement or rotation keys are being held
  34. bool isRotating = gVirtualInput().isButtonHeld(mRotateObj);
  35. // If switch to or from rotation mode, hide or show the cursor
  36. if (isRotating != mLastButtonState)
  37. {
  38. if (isRotating)
  39. Cursor::instance().hide();
  40. else
  41. Cursor::instance().show();
  42. mLastButtonState = isRotating;
  43. }
  44. // If we're rotating, apply new pitch/yaw rotation values depending on the amount of rotation from the
  45. // vertical/horizontal axes.
  46. float frameDelta = gTime().getFrameDelta();
  47. if (isRotating)
  48. {
  49. mYaw -= Degree(gVirtualInput().getAxisValue(mHorizontalAxis) * ROTATION_SPEED * frameDelta);
  50. mPitch -= Degree(gVirtualInput().getAxisValue(mVerticalAxis) * ROTATION_SPEED * frameDelta);
  51. mYaw = wrapAngle2(mYaw);
  52. mPitch = wrapAngle2(mPitch);
  53. Quaternion yRot;
  54. yRot.fromAxisAngle(Vector3::UNIT_Y, Radian(mYaw));
  55. Quaternion xRot;
  56. xRot.fromAxisAngle(Vector3::UNIT_X, Radian(mPitch));
  57. Quaternion camRot = yRot * xRot;
  58. camRot.normalize();
  59. SO()->setRotation(camRot);
  60. }
  61. }
  62. }