Touch.lua 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. -- Mobile framework for Android/iOS
  2. -- Gamepad from Ninja Snow War
  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. local GYROSCOPE_THRESHOLD = 0.1
  9. CAMERA_MIN_DIST = 1.0
  10. CAMERA_MAX_DIST = 20.0
  11. local zoom = false
  12. useGyroscope = false
  13. cameraDistance = 5.0
  14. function UpdateTouches(controls) -- Called from HandleUpdate
  15. zoom = false -- reset bool
  16. -- Zoom in/out
  17. if input.numTouches == 2 then
  18. local touch1 = input:GetTouch(0)
  19. local touch2 = input:GetTouch(1)
  20. -- Check for zoom pattern (touches moving in opposite directions and on empty space)
  21. if not touch1.touchedElement and not touch2.touchedElement and ((touch1.delta.y > 0 and touch2.delta.y < 0) or (touch1.delta.y < 0 and touch2.delta.y > 0)) then zoom = true else zoom = false end
  22. -- Check for zoom direction (in/out)
  23. if zoom then
  24. if Abs(touch1.position.y - touch2.position.y) > Abs(touch1.lastPosition.y - touch2.lastPosition.y) then sens = -1 else sens = 1 end
  25. cameraDistance = cameraDistance + Abs(touch1.delta.y - touch2.delta.y) * sens * TOUCH_SENSITIVITY / 50
  26. cameraDistance = Clamp(cameraDistance, CAMERA_MIN_DIST, CAMERA_MAX_DIST) -- Restrict zoom range to [1;20]
  27. end
  28. end
  29. -- Gyroscope (emulated by SDL through a virtual joystick)
  30. if useGyroscope and input.numJoysticks > 0 then -- numJoysticks = 1 on iOS & Android
  31. local joystick = input:GetJoystickByIndex(0) -- JoystickState
  32. if joystick.numAxes >= 2 then
  33. if joystick:GetAxisPosition(0) < -GYROSCOPE_THRESHOLD then controls:Set(CTRL_LEFT, true) end
  34. if joystick:GetAxisPosition(0) > GYROSCOPE_THRESHOLD then controls:Set(CTRL_RIGHT, true) end
  35. if joystick:GetAxisPosition(1) < -GYROSCOPE_THRESHOLD then controls:Set(CTRL_FORWARD, true) end
  36. if joystick:GetAxisPosition(1) > GYROSCOPE_THRESHOLD then controls:Set(CTRL_BACK, true) end
  37. end
  38. end
  39. end