1
+ ###
2
+ TouchController (stick + buttons) for touch devices
3
+ Based on the touch demo by Seb Lee-Delisle <http://seb.ly/>
4
+
5
+ @class bkcore.controllers.TouchController
6
+ @author Thibaut 'BKcore' Despoulain <http://bkcore.com>
7
+ ###
8
+ class TouchController
9
+
10
+ @ isCompatible: ->
11
+ return (' ontouchstart' of document .documentElement );
12
+
13
+ ###
14
+ Creates a new TouchController
15
+
16
+ @param dom DOMElement The element that will listen to touch events
17
+ @param stickMargin int The left margin in px for stick detection
18
+ @param buttonCallback function Callback for non-stick touches
19
+ ###
20
+ constructor : (@dom , @stickMargin = 200 , @buttonCallback = null ) ->
21
+ @active = true
22
+ @touches = null
23
+ @stickID = - 1
24
+ @stickPos = new Vec2 (0 , 0 )
25
+ @stickStartPos = new Vec2 (0 , 0 )
26
+ @stickVector = new Vec2 (0 , 0 )
27
+
28
+ @dom .addEventListener (' touchstart' , ((e )=> @ touchStart (e)), false )
29
+ @dom .addEventListener (' touchmove' , ((e )=> @ touchMove (e)), false )
30
+ @dom .addEventListener (' touchend' , ((e )=> @ touchEnd (e)), false )
31
+
32
+ ###
33
+ @private
34
+ ###
35
+ touchStart : (event ) ->
36
+ return if not @active
37
+ for touch in event .changedTouches
38
+ if @stickID < 0 and touch .clientX < @stickMargin
39
+ @stickID = touch .identifier
40
+ @stickStartPos .set (touch .clientX , touch .clientY )
41
+ @stickPos .copy (@stickStartPos )
42
+ @stickVector .set (0 , 0 )
43
+ continue
44
+ else
45
+ @buttonCallback ? (on , touch, event)
46
+ @touches = event .touches
47
+ false
48
+
49
+ ###
50
+ @private
51
+ ###
52
+ touchMove : (event ) ->
53
+ event .preventDefault ()
54
+ return if not @active
55
+ for touch in event .changedTouches
56
+ if @stickID is touch .identifier
57
+ @stickPos .set (touch .clientX , touch .clientY )
58
+ @stickVector .copy (@stickPos ).substract (@stickStartPos )
59
+ break
60
+ @touches = event .touches
61
+ false
62
+
63
+ ###
64
+ @private
65
+ ###
66
+ touchEnd : (event ) ->
67
+ return if not @active
68
+ @touches = event .touches
69
+ for touch in event .changedTouches
70
+ if @stickID is touch .identifier
71
+ @stickID = - 1
72
+ @stickVector .set (0 , 0 )
73
+ break
74
+ else
75
+ @buttonCallback ? (off , touch, event)
76
+ false
77
+
78
+ ###
79
+ Internal class used for vector2
80
+ @class Vec2
81
+ @private
82
+ ###
83
+ class Vec2
84
+
85
+ constructor : (@x = 0 , @y = 0 ) ->
86
+
87
+ substract : (vec ) ->
88
+ @x -= vec .x
89
+ @y -= vec .y
90
+ @
91
+
92
+ copy : (vec ) ->
93
+ @x = vec .x
94
+ @y = vec .y
95
+ @
96
+
97
+ set : (x , y ) ->
98
+ @x = x
99
+ @y = y
100
+ @
101
+
102
+ ###
103
+ Exports
104
+ @package bkcore
105
+ ###
106
+ exports = exports ? @
107
+ exports .bkcore ||= {}
108
+ exports .bkcore .controllers ||= {}
109
+ exports .bkcore .controllers .TouchController = TouchController
0 commit comments