File size: 1,858 Bytes
8194362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {
  Math as MathExtra,
  Vector3,
  Quaternion
} from 'three'

import ControlsBase from './ControlsBase'

export default class TouchControls extends ControlsBase {

  constructor (player, element) {
    super(player, element)

    this.velocity = new Vector3(0, 0, 0)

    this.onTouchEvent = this.onTouchEvent.bind(this)
  }

  onTouchEvent (event) {
    event.preventDefault()

    const touches = event.touches

    if (touches.length === 0) {
      this.velocity.set(0, 0, 0)
      return
    }

    let avgX = 0
    let avgY = 0
    for (let i = 0; i < touches.length; i++) {
      avgX += touches[i].pageX
      avgY += touches[i].pageY
    }
    avgX /= touches.length
    avgY /= touches.length

    const vy = Math.tan(0.5 * MathExtra.DEG2RAD * this.player.eyes.fov)
    const vx = this.player.eyes.aspect * vy

    this.velocity.set(
      vx * (avgX * 2.0 / window.innerWidth - 1.0),
      -vy * (avgY * 2.0 / window.innerHeight - 1.0),
      -1
    ).normalize()

    this.velocity.multiplyScalar(touches.length > 1 ? 10 : 1)
  }

  enable () {
    this.element.addEventListener('touchstart', this.onTouchEvent, false)
    this.element.addEventListener('touchmove', this.onTouchEvent, false)
    this.element.addEventListener('touchend', this.onTouchEvent, false)

    this.enabled = true
  }

  disable () {
    this.element.removeEventListener('touchstart', this.onTouchEvent, false)
    this.element.removeEventListener('touchmove', this.onTouchEvent, false)
    this.element.removeEventListener('touchend', this.onTouchEvent, false)

    this.enabled = false
  }

  update () {
    if (this.enabled === false) {
      return
    }

    const worldQuaternion = new Quaternion()

    this.player.eyes.getWorldQuaternion(worldQuaternion)

    this.player.velocity
      .copy(this.velocity)
      .applyQuaternion(worldQuaternion)
  }

}