forked from info498e-w17/lec08-patterns-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathball.ts
85 lines (76 loc) · 2.76 KB
/
ball.ts
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
class Ball
{
private diameter:number; //the diameter of the ball
private x:number; //the ball's x position
private y:number; //the ball's y position
private dx:number; //the speed the ball is moving along the x-axis
private dy:number; //the speed the ball is moving along the y-axis
private color:string; //the color of the ball
private static readonly TOP_BOUNDARY = 50;
private static readonly LEFT_BOUNDARY = 50;
private static readonly BOTTOM_BOUNDARY = 350;
private static readonly RIGHT_BOUNDARY = 350;
constructor() {
this.diameter = 40;
this.x = Math.floor(Math.random()*(Ball.RIGHT_BOUNDARY-Ball.LEFT_BOUNDARY))+Ball.LEFT_BOUNDARY;
this.y = Math.floor(Math.random()*(Ball.BOTTOM_BOUNDARY-Ball.TOP_BOUNDARY))+Ball.TOP_BOUNDARY;
this.dx = 3.5;
this.dy = 3.5;
this.color = "red";
}
/**
* Moves the bal its speed
*/
public move():void {
this.x += this.dx;
this.y += this.dy;
//check if hit the left wall
if(this.x < Ball.LEFT_BOUNDARY)
{
this.x = Ball.LEFT_BOUNDARY;
this.dx = -1*this.dx;
}
else if(this.x+this.diameter > Ball.RIGHT_BOUNDARY)
{
this.x = Ball.RIGHT_BOUNDARY - this.diameter;
this.dx = -1*this.dx;
}
if(this.y < Ball.TOP_BOUNDARY)
{
this.y = Ball.TOP_BOUNDARY;
this.dy = -1*this.dy;
}
else if(this.y+this.diameter > Ball.BOTTOM_BOUNDARY)
{
this.y = Ball.BOTTOM_BOUNDARY - this.diameter;
this.dy = -1*this.dy;
}
}
/**
* Determines if two balls intersect
* @param other The ball to check against
* @returns if they intersect
*/
public isTouching(other:Ball): boolean {
//use pythogorean theorum to calculate distance
let distance:number = Math.sqrt(
(this.x-other.x)*(this.x-other.x) + (this.y-other.y)*(this.y-other.y)
);
return distance < (this.diameter/2.0+other.diameter/2.0);
}
public bounceOff(other:Ball):void {
this.dx = -1*this.dx;
this.dy = -1*this.dy;
let distance:number = Math.sqrt(
(this.x-other.x)*(this.x-other.x) + (this.y-other.y)*(this.y-other.y)
);
let overlap = (this.diameter+other.diameter)/2.0 - distance;
if(overlap > 0) {
console.log("Bounce ! " + overlap);
this.x += Math.sign(this.dx)*(overlap*Math.sqrt(2)/2);
this.y += Math.sign(this.dy)*(overlap*Math.sqrt(2)/2);
}
}
}
//workaround for targeting ES5 (https://github.com/Microsoft/TypeScript/issues/6907)
interface Math { sign(x: number): number; }