Touch.as 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Mobile framework for Android/iOS
  2. // Gamepad from NinjaSnowWar
  3. // Touches patterns:
  4. // - 1 finger touch = pick object through raycast
  5. // - 1 or 2 fingers drag = rotate camera
  6. // - 2 fingers sliding in opposite direction (up/down) = zoom in/out
  7. // Setup: Call the update function 'UpdateTouches()' from HandleUpdate or equivalent update handler function
  8. const float GYROSCOPE_THRESHOLD = 0.1;
  9. const float CAMERA_MIN_DIST = 1.0f;
  10. const float CAMERA_MAX_DIST = 20.0f;
  11. bool zoom = false;
  12. bool useGyroscope = false;
  13. float cameraDistance = 5.0;
  14. void UpdateTouches(Controls& controls) // Called from HandleUpdate
  15. {
  16. zoom = false; // reset bool
  17. // Zoom in/out
  18. if (input.numTouches == 2)
  19. {
  20. TouchState@ touch1 = input.touches[0];
  21. TouchState@ touch2 = input.touches[1];
  22. // Check for zoom pattern (touches moving in opposite directions)
  23. if (touch1.touchedElement is null && touch2.touchedElement is null && ((touch1.delta.y > 0 && touch2.delta.y < 0) || (touch1.delta.y < 0 && touch2.delta.y > 0)))
  24. zoom = true;
  25. else
  26. zoom = false;
  27. if (zoom)
  28. {
  29. int sens = 0;
  30. // Check for zoom direction (in/out)
  31. if (Abs(touch1.position.y - touch2.position.y) > Abs(touch1.lastPosition.y - touch2.lastPosition.y))
  32. sens = -1;
  33. else
  34. sens = 1;
  35. cameraDistance += Abs(touch1.delta.y - touch2.delta.y) * sens * TOUCH_SENSITIVITY / 50;
  36. cameraDistance = Clamp(cameraDistance, CAMERA_MIN_DIST, CAMERA_MAX_DIST); // Restrict zoom range to [1;20]
  37. }
  38. }
  39. // Gyroscope (emulated by SDL through a virtual joystick)
  40. if (input.numJoysticks > 0) // numJoysticks = 1 on iOS & Android
  41. {
  42. JoystickState@ joystick = input.joysticksByIndex[0];
  43. if (joystick.numAxes >= 2)
  44. {
  45. if (joystick.axisPosition[0] < -GYROSCOPE_THRESHOLD)
  46. controls.Set(CTRL_LEFT, true);
  47. if (joystick.axisPosition[0] > GYROSCOPE_THRESHOLD)
  48. controls.Set(CTRL_RIGHT, true);
  49. if (joystick.axisPosition[1] < -GYROSCOPE_THRESHOLD)
  50. controls.Set(CTRL_FORWARD, true);
  51. if (joystick.axisPosition[1] > GYROSCOPE_THRESHOLD)
  52. controls.Set(CTRL_BACK, true);
  53. }
  54. }
  55. }