-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathballs.html
115 lines (92 loc) · 2.48 KB
/
balls.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Balls in three.js</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script>
const W = 50;
const N = 200;
function rand() {
return Math.random()*2 - 1;
}
function norm(v) {
return v.x * v.x + v.y * v.y + v.z * v.z;
}
function Sphere() {
const R = 0.5 + Math.random();
const geometry = new THREE.SphereGeometry(R);
const material = new THREE.MeshNormalMaterial( );
const mesh = new THREE.Mesh( geometry, material );
this.mesh = mesh;
this.radius = R;
this.position = {x: W*rand(), y: W*rand(), z: W*rand()};
this.velocity = {x: rand(), y: rand(), z: rand()};
}
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var entities = [];
for (let i=0; i<N; i++) {
entities[i] = new Sphere();
}
for (let e of entities) {
scene.add( e.mesh );
draw(e);
}
camera.position.z = 100;
function cube_bounce(p, v) {
let nx = p.x + v.x;
let ny = p.y + v.y;
let nz = p.z + v.z;
// TODO: handle object width
if (nx >= W)
{ nx = 2 * W - nx; v.x = -v.x; }
if (ny >= W)
{ ny = 2 * W - ny; v.y = -v.y; }
if (nz >= W)
{ nz = 2 * W - nz; v.z = -v.z; }
if (nx <= -W)
{ nx = -2 * W - nx; v.x = -v.x; }
if (ny <= -W)
{ ny = -2 * W - ny; v.y = -v.y; }
if (nz <= -W)
{ nz = -2 * W - nz; v.z = -v.z; }
p.x = nx;
p.y = ny;
p.z = nz;
}
function update_entity(e) {
e.position.x += e.velocity.x;
e.position.y += e.velocity.y;
e.position.z += e.velocity.z;
cube_bounce(e.mesh.position, e.velocity);
}
function draw(e) {
e.mesh.position.x = e.position.x;
e.mesh.position.y = e.position.y;
e.mesh.position.z = e.position.z;
}
function handle_collisions() {
for (let i = 0; i < e.length - 1; i++) {
for (let j = i + 1; j < e.length; j++) {
}
}
function animate() {
requestAnimationFrame( animate );
entities.forEach(update_entity);
handle_collisions();
entities.forEach(draw);
renderer.render( scene, camera );
}
animate();
</script>
</body>
</html>