forked from xem/mini2Dphysics
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
509 lines (420 loc) · 14.2 KB
/
index.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
<canvas id=a width=800 height=450></canvas>
<script>
c = a.getContext('2d');
// MINI 2D PHYSICS
// ===============
// 2D vector tools
var Vec2 = (x,y) => ({x,y});
var length = v => dot(v,v)**.5;
var add = (v,w) => Vec2(v.x + w.x, v.y + w.y);
var substract = (v,w) => add(v, scale(w, -1));
var scale = (v,n) => Vec2(v.x * n, v.y * n);
var dot = (v,w) => v.x * w.x + v.y * w.y;
var cross = (v,w) => v.x * w.y - v.y * w.x;
var rotate = (v, center, angle, x = v.x - center.x, y = v.y - center.y) => Vec2(x * Math.cos(angle) - y * Math.sin(angle) + center.x, x * Math.sin(angle) + y * Math.cos(angle) + center.y);
var normalize = v => scale(v, 1 / (length(v) || 1));
var distance = (v,w) => length(substract(v,w));
// Gravity
var mGravity = Vec2(0, 100);
// All shapes
var objects = [];
// Collision info
var collisionInfo = {}; // final collision between two shapes
var collisionInfoR1 = {}; // temp collision: rect 1 vs rect 2
var collisionInfoR2 = {}; // temp collision: rect 1 vs rect 1
// Collision info setter
var setInfo = (collision, D, N, S) => {
collision.D = D; // depth
collision.N = N; // normal
collision.S = S; // start
collision.E = add(S, scale(N, D)); // end
};
// New shape
var RigidShape = (C, mass, F, R, T, B, W, H, shape) => {
shape = {
T, // 0 circle / 1 rectangle
C, // center
F, // friction
R, // restitution (bouncing)
M: mass ? 1 / mass : 0, // inverseMass (0 if immobile)
V: Vec2(0, 0), // velocity (speed)
A: mass ? mGravity : Vec2(0, 0), // acceleration
G: 0, // angle
v: 0, // angle velocity
a: 0, // angle acceleration
B, // (bounds) radius
W, // width
H, // height
I: T // inertia
? (Math.hypot(W, H) / 2, mass > 0 ? 1 / (mass * (W ** 2 + H ** 2) / 12) : 0) // rectangle
: (mass > 0 ? (mass * B ** 2) / 12 : 0), // circle
N: [], // face normals array (rectangles)
X: [ // Vertex: 0: TopLeft, 1: TopRight, 2: BottomRight, 3: BottomLeft (rectangles)
Vec2(C.x - W / 2, C.y - H / 2),
Vec2(C.x + W / 2, C.y - H / 2),
Vec2(C.x + W / 2, C.y + H / 2),
Vec2(C.x - W / 2, C.y + H / 2)
]
};
// Prepare rectangle
if(T /* == 1 */){
computeRectNormals(shape);
}
objects.push(shape);
return shape;
};
// Move a shape along a vector
var moveShape = (shape, v, i) => {
// Center
shape.C = add(shape.C, v);
// Rectangle (move vertex)
if(shape.T){
for(i = 4; i--;){
shape.X[i] = add(shape.X[i], v);
}
}
}
// Rotate a shape around its center
var rotateShape = (shape, angle, i) => {
// Update angle
shape.G += angle;
// Rectangle (rotate vertex)
if(shape.T){
for(i = 4; i--;){
shape.X[i] = rotate(shape.X[i], shape.C, angle);
}
computeRectNormals(shape);
}
}
// Test if two shapes have intersecting bounding circles
var boundTest = (s1, s2) => length(substract(s2.C, s1.C)) <= s1.B + s2.B;
// Compute face normals (for rectangles)
var computeRectNormals = (shape, i) => {
// N: normal of each face toward outside of rectangle
// 0: Top, 1: Right, 2: Bottom, 3: Left
for(i = 4; i--;){
shape.N[i] = normalize(substract(shape.X[(i+1) % 4], shape.X[(i+2) % 4]));
}
}
// Find the axis of least penetration between two rects
var findAxisLeastPenetration = (rect, otherRect, collisionInfo) => {
var
n,
i,
j,
supportPoint,
bestDistance = 1e9,
bestIndex = -1,
hasSupport = 1,
tmpSupportPoint,
tmpSupportPointDist;
for(i = 4; hasSupport && i--;){
// Retrieve a face normal from A
n = rect.N[i];
// use -n as direction and the vertex on edge i as point on edge
var
dir = scale(n, -1),
ptOnEdge = rect.X[i],
// find the support on B
vToEdge,
projection;
tmpSupportPointDist = -1e9;
tmpSupportPoint = -1;
// check each vector of other object
for(j = 4; j--;){
vToEdge = substract(otherRect.X[j], ptOnEdge);
projection = dot(vToEdge, dir);
// find the longest distance with certain edge
// dir is -n direction, so the distance should be positive
if(projection > 0 && projection > tmpSupportPointDist){
tmpSupportPoint = otherRect.X[j];
tmpSupportPointDist = projection;
}
}
hasSupport = (tmpSupportPoint !== -1);
// get the shortest support point depth
if(hasSupport && tmpSupportPointDist < bestDistance){
bestDistance = tmpSupportPointDist;
bestIndex = i;
supportPoint = tmpSupportPoint;
}
}
if(hasSupport){
// all four directions have support point
setInfo(collisionInfo, bestDistance, rect.N[bestIndex], add(supportPoint, scale(rect.N[bestIndex], bestDistance)));
}
return hasSupport;
};
// Test collision between two shapes
var testCollision = (c1, c2, info) => {
// Circle vs circle
if(!c1.T && !c2.T){
var
vFrom1to2 = substract(c2.C, c1.C),
rSum = c1.B + c2.B,
dist = length(vFrom1to2);
if(dist <= Math.sqrt(rSum * rSum)){
//if(dist){
// overlapping but not same position
var
normalFrom2to1 = normalize(scale(vFrom1to2, -1)),
radiusC2 = scale(normalFrom2to1, c2.B);
setInfo(collisionInfo, rSum - dist, normalize(vFrom1to2), add(c2.C, radiusC2));
//}
/*
// same position
else {
if(c1.B > c2.B){
setInfo(collisionInfo, rSum, Vec2(0, -1), add(c1.C, Vec2(0, c1.B)));
}
else {
setInfo(collisionInfo, rSum, Vec2(0, -1), add(c2.C, Vec2(0, c2.B)));
}
}
*/
}
return 1;
}
// Rect vs Rect
if(c1.T /*== 1*/ && c2.T /*== 1*/){
var
status1 = 0,
status2 = 0;
// find Axis of Separation for both rectangles
status1 = findAxisLeastPenetration(c1, c2, collisionInfoR1);
if(status1){
status2 = findAxisLeastPenetration(c2, c1, collisionInfoR2);
if(status2){
// if both of rectangles are overlapping, choose the shorter normal as the normal
if(collisionInfoR1.D < collisionInfoR2.D){
setInfo(collisionInfo, collisionInfoR1.D, collisionInfoR1.N, substract(collisionInfoR1.S, scale(collisionInfoR1.N, collisionInfoR1.D)));
}
else {
setInfo(collisionInfo, collisionInfoR2.D, scale(collisionInfoR2.N, -1), collisionInfoR2.S);
}
}
}
return status1 && status2;
}
// Rectangle vs Circle
// (c1 is the rectangle and c2 is the circle, invert the two if needed)
if(!c1.T && c2.T /*== 1*/){
[c1, c2] = [c2, c1];
}
if(c1.T /*== 1*/ && !c2.T){
var
inside = 1,
bestDistance = -1e9,
nearestEdge = 0,
i, v,
circ2Pos, projection;
for(i = 4; i--;){
// find the nearest face for center of circle
circ2Pos = c2.C;
v = substract(circ2Pos, c1.X[i]);
projection = dot(v, c1.N[i]);
if(projection > 0){
// if the center of circle is outside of c1angle
bestDistance = projection;
nearestEdge = i;
inside = 0;
break;
}
if(projection > bestDistance){
bestDistance = projection;
nearestEdge = i;
}
}
var dis, normal;
if(inside){
// the center of circle is inside of c1angle
setInfo(collisionInfo, c2.B - bestDistance, c1.N[nearestEdge], substract(circ2Pos, scale(c1.N[nearestEdge], c2.B)));
}
else {
// the center of circle is outside of c1angle
// v1 is from left vertex of face to center of circle
// v2 is from left vertex of face to right vertex of face
var
v1 = substract(circ2Pos, c1.X[nearestEdge]),
v2 = substract(c1.X[(nearestEdge + 1) % 4], c1.X[nearestEdge]),
dotp = dot(v1, v2);
if(dotp < 0){
// the center of circle is in corner region of X[nearestEdge]
dis = length(v1);
// compare the distance with radium to decide collision
if(dis > c2.B){
return;
}
normal = normalize(v1);
setInfo(collisionInfo, c2.B - dis, normal, add(circ2Pos, scale(normal, -c2.B)));
}
else {
// the center of circle is in corner region of X[nearestEdge+1]
// v1 is from right vertex of face to center of circle
// v2 is from right vertex of face to left vertex of face
v1 = substract(circ2Pos, c1.X[(nearestEdge + 1) % 4]);
v2 = scale(v2, -1);
dotp = dot(v1, v2);
if(dotp < 0){
dis = length(v1);
// compare the distance with radium to decide collision
if(dis > c2.B){
return;
}
normal = normalize(v1);
setInfo(collisionInfo, c2.B - dis, normal, add(circ2Pos, scale(normal, -c2.B)));
}
else {
// the center of circle is in face region of face[nearestEdge]
if(bestDistance < c2.B){
setInfo(collisionInfo, c2.B - bestDistance, c1.N[nearestEdge], substract(circ2Pos, scale(c1.N[nearestEdge], c2.B)));
}
else {
return;
}
}
}
}
return 1;
}
};
var resolveCollision = (s1, s2, collisionInfo) => {
if(!s1.M && !s2.M){
return;
}
// correct positions
var
num = collisionInfo.D / (s1.M + s2.M) * .8, // .8 = poscorrectionrate = percentage of separation to project objects
correctionAmount = scale(collisionInfo.N, num),
n = collisionInfo.N;
moveShape(s1, scale(correctionAmount, -s1.M));
moveShape(s2, scale(correctionAmount, s2.M));
// the direction of collisionInfo is always from s1 to s2
// but the Mass is inversed, so start scale with s2 and end scale with s1
var
start = scale(collisionInfo.S, s2.M / (s1.M + s2.M)),
end = scale(collisionInfo.E, s1.M / (s1.M + s2.M)),
p = add(start, end),
// r is vector from center of object to collision point
r1 = substract(p, s1.C),
r2 = substract(p, s2.C),
// newV = V + v cross R
v1 = add(s1.V, Vec2(-1 * s1.v * r1.y, s1.v * r1.x)),
v2 = add(s2.V, Vec2(-1 * s2.v * r2.y, s2.v * r2.x)),
relativeVelocity = substract(v2, v1),
// Relative velocity in normal direction
rVelocityInNormal = dot(relativeVelocity, n);
// if objects moving apart ignore
if(rVelocityInNormal > 0){
return;
}
// compute and apply response impulses for each object
var
newRestituion = Math.min(s1.R, s2.R),
newFriction = Math.min(s1.F, s2.F),
// R cross N
R1crossN = cross(r1, n),
R2crossN = cross(r2, n),
// Calc impulse scalar
// the formula of jN can be found in http://www.myphysicslab.com/collision.html
jN = (-(1 + newRestituion) * rVelocityInNormal) / (s1.M + s2.M + R1crossN * R1crossN * s1.I + R2crossN * R2crossN * s2.I),
// impulse is in direction of normal ( from s1 to s2)
impulse = scale(n, jN);
// impulse = F dt = m * ?v
// ?v = impulse / m
s1.V = substract(s1.V, scale(impulse, s1.M));
s2.V = add(s2.V, scale(impulse, s2.M));
s1.v -= R1crossN * jN * s1.I;
s2.v += R2crossN * jN * s2.I;
var
tangent = scale(normalize(substract(relativeVelocity, scale(n, dot(relativeVelocity, n)))), -1),
R1crossT = cross(r1, tangent),
R2crossT = cross(r2, tangent),
jT = (-(1 + newRestituion) * dot(relativeVelocity, tangent) * newFriction) / (s1.M + s2.M + R1crossT * R1crossT * s1.I + R2crossT * R2crossT * s2.I);
// friction should less than force in normal direction
if(jT > jN){
jT = jN;
}
// impulse is from s1 to s2 (in opposite direction of velocity)
impulse = scale(tangent, jT);
s1.V = substract(s1.V, scale(impulse, s1.M));
s2.V = add(s2.V, scale(impulse,s2.M));
s1.v -= R1crossT * jT * s1.I;
s2.v += R2crossT * jT * s2.I;
};
// Loop
setInterval(
(i,j,k) => {
// Reset
a.width ^= 0;
// Compute collisions
for(k = 9; k--;){
for(i = objects.length; i--;){
for(j = objects.length; j-- > i;){
// Test bounds
if(boundTest(objects[i], objects[j])){
// Test collision
if(testCollision(objects[i], objects[j], collisionInfo)){
// Make sure the normal is always from object[i] to object[j]
if(dot(collisionInfo.N, substract(objects[j].C, objects[i].C)) < 0){
collisionInfo = {
D: collisionInfo.D,
N: scale(collisionInfo.N, -1),
S: collisionInfo.E,
E: collisionInfo.S
};
}
// Resolve collision
resolveCollision(objects[i], objects[j], collisionInfo);
}
}
}
}
}
// Draw / Update scene
for(i = objects.length; i--;){
// Draw
// ----
c.save();
c.translate(objects[i].C.x, objects[i].C.y);
c.rotate(objects[i].G);
// Circle
if(!objects[i].T){
c.beginPath();
c.arc(0, 0, objects[i].B, 0, 7);
c.lineTo(0, 0);
c.closePath();
c.stroke();
}
// Rectangle
else {//if(objects[i].T == 1){
c.strokeRect(-objects[i].W / 2, -objects[i].H / 2, objects[i].W, objects[i].H);
}
c.restore();
// Update position/rotation
objects[i].V = add(objects[i].V, scale(objects[i].A, 1/60));
moveShape(objects[i], scale(objects[i].V, 1/60));
objects[i].v += objects[i].a * 1/60;
rotateShape(objects[i], objects[i].v * 1/60);
}
},
16
);
// New circle
var Circle = (center, radius, mass, friction, restitution) => RigidShape(center, mass, friction, restitution, 0, radius);
// New rectangle
var Rectangle = (center, width, height, mass, friction, restitution) => RigidShape(center, mass, friction, restitution, 1, Math.hypot(width, height)/2, width, height);
// DEMO
// ====
r = Rectangle(Vec2(500, 200), 400, 20, 0, 1, .5);
rotateShape(r, 2.8);
Rectangle(Vec2(200, 400), 400, 20, 0, 1, .5);
Rectangle(Vec2(100, 200), 200, 20, 0, 1, .5);
Rectangle(Vec2(10, 360), 20, 100, 0, 1, .5);
for(var i = 0; i < 30; i++){
r = Circle(Vec2(Math.random() * 800, Math.random() * 450 / 2), Math.random() * 20 + 10, Math.random() * 30, Math.random() / 2, Math.random() / 2);
rotateShape(r, Math.random() * 7);
r = Rectangle(Vec2(Math.random() * 800, Math.random() * 450 / 2), Math.random() * 20 + 10, Math.random() * 20 + 10, Math.random() * 30, Math.random() / 2, Math.random() / 2);
rotateShape(r, Math.random() * 7);
}
</script>