-
Notifications
You must be signed in to change notification settings - Fork 0
/
ball.html
121 lines (86 loc) · 3.41 KB
/
ball.html
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<! DOCTYPE html>
<html>
<head>
<title>Ball</title>
</head>
<body>
<canvas id = "myCanvas" style = "border: 2px solid"></canvas>
<script>
// canvas setup
var canvas = document.getElementById("myCanvas"); // get canvas
var c = canvas.getContext("2d"); // get context
canvas.width = window.innerWidth - 20; // set width, height to inner width and height of the window with margin
canvas.height = window.innerHeight - 100;
var simMinWidth = 20.0; //minimum width of the screen regardless of the format
var cScale = Math.min(canvas.width, canvas.height) / simMinWidth;
var simWidth = canvas.width /cScale;
var sinHeight = canvas.height / cScale;
var deltaT = 10; //time step, ms
function cX(pos){
return pos.x * cScale;
}
function cY(pos){
return canvas.height - pos.y * cScale;
}
// utility
function getRando(min, max) {
return Math.random() * (max - min) + min;
}
// scene
var ball = {
radius : 0.5,
pos : {x : canvas.width/(2*cScale), y : 0.8*canvas.height/(cScale) - 0.5},
velo : {x : getRando(-100, 100), y : getRando(-100, 100)},
};
// drawing
function draw(){
c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = "#FF0000";
// draw circle
c.beginPath();
c.arc(
cX(ball.pos), cY(ball.pos), cScale * ball.radius, 0.0, 2.0 * Math.PI
);
c.closePath();
c.fill();
}
var accel = {
x : 0,
y : -100,
};
// simulation
function simulate(){
if (0.5 < ball.pos.y < canvas.height/cScale - 0.6){
ball.pos.y = (1/2) * accel.y * (deltaT/1000)**2 + ball.velo.y * (deltaT/1000) + ball.pos.y;
ball.velo.y = ball.velo.y + (accel.y * (deltaT/1000));
}
if (0.5 < ball.pos.x < canvas.width/cScale - 0.6){
ball.pos.x = (1/2) * accel.x * (deltaT/1000)**2 + ball.velo.x * (deltaT/1000) + ball.pos.x;
ball.velo.x = ball.velo.x + (accel.x * (deltaT/1000));
}
if (ball.pos.y < 0.5){
ball.pos.y = 0.49;
ball.velo.y = -(0.9*ball.velo.y);
}
if (ball.pos.y > canvas.height/cScale - 0.5){
ball.pos.y = canvas.height/cScale - 0.51;
ball.velo.y = -(0.9*ball.velo.y);
}
if (ball.pos.x < 0.5){
ball.pos.x = 0.49;
ball.velo.x = -(0.9*ball.velo.x);
}
if (ball.pos.x > canvas.width/cScale - 0.5){
ball.pos.x = canvas.width/cScale - 0.51;
ball.velo.x = -(0.9*ball.velo.x);
}
}
function update(){
setTimeout(simulate, 10)
draw();
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>