-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ball.js
95 lines (87 loc) · 2.6 KB
/
Ball.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
function Ball() {
/*=========
Variables
=========*/
var that; // pointer to "this" [Private]
var moving; // boolean of whether ball is moving [Private]
var vx; // x-component of ball's velocity [Private]
var vy; // y-component of ball's velocity [Private]
this.x; // x-coordinate of ball's position [Public]
this.y; // y-coordinate of ball's position [Public]
/*===========
Constructor
===========*/
that = this;
moving = false;
vx = 0;
vy = 0;
this.x = Pong.WIDTH/2;
this.y = Pong.HEIGHT/2;
/*========================
updateVelocity [Private]
=======================*/
var updateVelocity = function(px) {
// Change direction (vx) depending on collision point between ball and paddle
if (that.x >= px - Paddle.R1 && that.x <= px + Paddle.R1) {
vy = -vy;
} else if (that.x >= px - Paddle.R2 && that.x <= px + Paddle.R2) {
vx += (that.x > px? 1 : -1);
vy = -vy;
} else if (that.x >= px - Paddle.R3 && that.x <= px + Paddle.R3) {
vx += (that.x > px? 2 : -2);
vy = -vy;
} else if (that.x + Ball.WIDTH/2 >= px - Paddle.WIDTH/2 && that.x - Ball.WIDTH/2 <= px + Paddle.WIDTH/2) {
vx += (that.x > px? 3 : -3);
vy = -vy;
}
// else = ball didn't collide with paddle
}
/*========================
startMoving [Privileged]
========================*/
this.startMoving = function(){
vx = 0;
vy = Ball.VERTICAL_VELOCITY;
moving = true;
}
/*=====================
isMoving [Privileged]
=====================*/
this.isMoving = function() {
return moving;
}
/*========================
moveOneStep [Privileged]
========================*/
this.moveOneStep = function(topPaddle, bottomPaddle) {
// New position
that.x += vx;
that.y += vy;
// Check for bouncing
if (that.x <= Ball.WIDTH/2 || that.x >= Pong.WIDTH - Ball.WIDTH/2) {
// Bounds off horizontally
vx = -vx;
} else if (that.y + Ball.HEIGHT/2 > Pong.HEIGHT || that.y - Ball.HEIGHT/2 < 0) {
// Goes out of bound! Lose point and restart.
that.x = Pong.WIDTH/2;
that.y = Pong.HEIGHT/2;
vx = 0;
vy = 0;
moving = false;
} else if (that.y - Ball.HEIGHT/2 < Paddle.HEIGHT) {
// Chance for ball to collide with top paddle.
updateVelocity(topPaddle.x);
} else if (that.y + Ball.HEIGHT/2 > Pong.HEIGHT - Paddle.HEIGHT) {
// Chance for ball to collide with bottom paddle.
updateVelocity(bottomPaddle.x);
}
}
}
/*================
Static Variables
================*/
Ball.WIDTH = 10;
Ball.HEIGHT = 10;
Ball.VERTICAL_VELOCITY = 7;
// For node.js require
global.Ball = Ball;