Touch.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Graphics/Graphics.h>
  4. #include <Urho3D/Graphics/Renderer.h>
  5. #include <Urho3D/Input/Controls.h>
  6. #include <Urho3D/Input/Input.h>
  7. #include "Character.h"
  8. #include "Touch.h"
  9. const float GYROSCOPE_THRESHOLD = 0.1f;
  10. Touch::Touch(Context* context, float touchSensitivity) :
  11. Object(context),
  12. touchSensitivity_(touchSensitivity),
  13. cameraDistance_(CAMERA_INITIAL_DIST),
  14. zoom_(false),
  15. useGyroscope_(false)
  16. {
  17. }
  18. Touch::~Touch() = default;
  19. void Touch::UpdateTouches(Controls& controls) // Called from HandleUpdate
  20. {
  21. zoom_ = false; // reset bool
  22. auto* input = GetSubsystem<Input>();
  23. // Zoom in/out
  24. if (input->GetNumTouches() == 2)
  25. {
  26. TouchState* touch1 = input->GetTouch(0);
  27. TouchState* touch2 = input->GetTouch(1);
  28. // Check for zoom pattern (touches moving in opposite directions and on empty space)
  29. if (!touch1->touchedElement_ && !touch2->touchedElement_ && ((touch1->delta_.y_ > 0 && touch2->delta_.y_ < 0) || (touch1->delta_.y_ < 0 && touch2->delta_.y_ > 0)))
  30. zoom_ = true;
  31. else
  32. zoom_ = false;
  33. if (zoom_)
  34. {
  35. int sens = 0;
  36. // Check for zoom direction (in/out)
  37. if (Abs(touch1->position_.y_ - touch2->position_.y_) > Abs(touch1->lastPosition_.y_ - touch2->lastPosition_.y_))
  38. sens = -1;
  39. else
  40. sens = 1;
  41. cameraDistance_ += Abs(touch1->delta_.y_ - touch2->delta_.y_) * sens * touchSensitivity_ / 50.0f;
  42. cameraDistance_ = Clamp(cameraDistance_, CAMERA_MIN_DIST, CAMERA_MAX_DIST); // Restrict zoom range to [1;20]
  43. }
  44. }
  45. // Gyroscope (emulated by SDL through a virtual joystick)
  46. if (useGyroscope_ && input->GetNumJoysticks() > 0) // numJoysticks = 1 on iOS & Android
  47. {
  48. JoystickState* joystick = input->GetJoystickByIndex(0);
  49. if (joystick->GetNumAxes() >= 2)
  50. {
  51. if (joystick->GetAxisPosition(0) < -GYROSCOPE_THRESHOLD)
  52. controls.Set(CTRL_LEFT, true);
  53. if (joystick->GetAxisPosition(0) > GYROSCOPE_THRESHOLD)
  54. controls.Set(CTRL_RIGHT, true);
  55. if (joystick->GetAxisPosition(1) < -GYROSCOPE_THRESHOLD)
  56. controls.Set(CTRL_FORWARD, true);
  57. if (joystick->GetAxisPosition(1) > GYROSCOPE_THRESHOLD)
  58. controls.Set(CTRL_BACK, true);
  59. }
  60. }
  61. }