forked from jcemer/telepong
-
Notifications
You must be signed in to change notification settings - Fork 0
/
paddle.js
executable file
·68 lines (52 loc) · 1.73 KB
/
paddle.js
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
;(function (exports) {
var KEY = {
right: 39
, left: 37
}
function Paddle(game) {
this.game = game
this.width = this.game.stage.width / 3
this.x = this.game.stage.width / 2
this.setListeners()
}
Paddle.prototype.setListeners = function () {
document.addEventListener('keydown', this.onKeydown.bind(this), false)
document.addEventListener('keyup', this.onKeyup.bind(this), false)
document.addEventListener('touchstart', this.onTouchstart.bind(this), false)
document.addEventListener('touchmove', this.onTouchmove.bind(this), false)
}
Paddle.prototype.onKeydown = function (event) {
var gap = this.game.stage.width / 30
clearInterval(this.keysInterval)
if (event.which == KEY.right) {
gap *= 1
} else if (event.which == KEY.left) {
gap *= -1
} else {
return
}
this.move(gap)
this.keysInterval = setInterval(this.move.bind(this, gap), 100)
}
Paddle.prototype.onKeyup = function (event) {
clearInterval(this.keysInterval)
}
Paddle.prototype.onTouchstart = function (event) {
this.touchX = event.touches[0].pageX
}
Paddle.prototype.onTouchmove = function (event) {
var x = event.touches[0].pageX
event.preventDefault()
this.move(x - this.touchX)
this.touchX = x
}
Paddle.prototype.move = function (gap) {
this.x += gap
this.boundsX()
}
Paddle.prototype.boundsX = function () {
this.x = Math.min(this.x, this.game.stage.width - this.width)
this.x = Math.max(this.x, 0)
}
exports.Paddle = Paddle
})(window.Telepong)