| 1 | export default createTouchControl; |
| 2 | |
| 3 | function createTouchControl(renderer) { |
| 4 | var api = { |
| 5 | destroy: destroy |
| 6 | }; |
| 7 | var wasdControls, touchControls; |
| 8 | |
| 9 | init(); |
| 10 | |
| 11 | return api; |
| 12 | |
| 13 | function init() { |
| 14 | var container = renderer.getContainer(); |
| 15 | container.addEventListener('touchstart', onTouchStart, false); |
| 16 | container.addEventListener('touchend', onTouchEnd, false); |
| 17 | |
| 18 | // todo: should this be part of unrender itself? |
| 19 | wasdControls = renderer.input(); |
| 20 | if (window.orientation !== undefined) { |
| 21 | var camera = renderer.camera(); |
| 22 | touchControls = require('three.orientation')(camera); |
| 23 | renderer.onFrame(updateFromDeviceOritentation); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | function updateFromDeviceOritentation() { |
| 28 | touchControls.update(); |
| 29 | } |
| 30 | |
| 31 | function destroy() { |
| 32 | var container = renderer.getContainer(); |
| 33 | container.removeEventListener('touchstart', onTouchStart, false); |
| 34 | container.removeEventListener('touchend', onTouchEnd, false); |
| 35 | if (touchControls) { |
| 36 | touchControls.disconnect(); |
| 37 | renderer.offFrame(updateFromDeviceOritentation); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | function onTouchStart(e) { |
| 42 | if (!e.touches) return; |
| 43 | |
| 44 | if (e.touches.length > 0) { |
| 45 | wasdControls.moveState.forward = (e.touches.length === 1); |
| 46 | wasdControls.moveState.back = (e.touches.length === 2); |
| 47 | wasdControls.updateMovementVector(); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | function onTouchEnd(e) { |
| 52 | if (!e.touches) return; |
| 53 | wasdControls.moveState.forward = (e.touches.length === 1); |
| 54 | wasdControls.moveState.back = (e.touches.length === 2); |
| 55 | wasdControls.updateMovementVector(); |
| 56 | } |
| 57 | } |