ObjectRotator.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 = 1.0f;
  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. if (isRotating)
  47. {
  48. mYaw -= Degree(gVirtualInput().getAxisValue(mHorizontalAxis) * ROTATION_SPEED);
  49. mPitch -= Degree(gVirtualInput().getAxisValue(mVerticalAxis) * ROTATION_SPEED);
  50. mYaw = wrapAngle2(mYaw);
  51. mPitch = wrapAngle2(mPitch);
  52. Quaternion yRot;
  53. yRot.fromAxisAngle(Vector3::UNIT_Y, Radian(mYaw));
  54. Quaternion xRot;
  55. xRot.fromAxisAngle(Vector3::UNIT_X, Radian(mPitch));
  56. Quaternion camRot = yRot * xRot;
  57. camRot.normalize();
  58. SO()->setRotation(camRot);
  59. }
  60. }
  61. }