-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEngine.js
444 lines (381 loc) · 12.3 KB
/
Engine.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
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
import { Ball } from './Ball.js';
import { Vector2 } from './Vector2.js';
/**
* Physics engine that handles physics objects
*/
export class Engine {
/**
* Creates engine
* @param {HTMLCanvasElement} canvas - Canvas to draw objects on.
* @param {number} width - Width of canvas.
* @param {number} height - Height of canvas.
* @param {String} backgrndColor - CSS color value.
* @param {Array.<Ball>} physObjects - Array of physics objects in the engine.
*
*/
constructor(
canvas,
backgrndColor,
borderWidth = 0,
physObjects = new Array(0)
) {
canvas.style.borderWidth = borderWidth + 'px';
this.canvas = canvas;
this.canvas2D = this.canvas.getContext('2d');
this.backgrndColor = backgrndColor;
this.borderWidth = borderWidth;
this.physObjects = physObjects;
this.width = canvas.width;
this.height = canvas.height;
this.timeStamp = 0;
this.elapsedTime = 0;
this.mouseTimeStamp = 0;
this.mouseElapsedTime = 0;
this.selectedObject = null;
this.mouseHeld = false;
this.mousePos = new Vector2();
this.mouseVel = new Vector2();
this.isStopped = false;
this.boundOnMouseUp = this.onMouseUp.bind(this);
this.boundOnMouseDown = this.onMouseDown.bind(this);
this.boundOnMouseMove = this.onMouseMove.bind(this);
this.boundOnTouchStart = this.onTouchStart.bind(this);
this.boundOnTouchMove = this.onTouchMove.bind(this);
this.onObjectPress = function () {};
this.onObjectRelease = function () {};
this.whileObjectHeld = function () {};
this.onStop = () => {};
this.onFrame = () => {};
canvas.width = canvas.height * (canvas.clientWidth / canvas.clientHeight); //Ensure correct aspect ratio of canvas
window.addEventListener('mouseup', this.boundOnMouseUp);
window.addEventListener('mousedown', this.boundOnMouseDown);
window.addEventListener('mousemove', this.boundOnMouseMove);
window.addEventListener('touchstart', this.boundOnTouchStart);
window.addEventListener('touchend', this.boundOnMouseUp);
window.addEventListener('touchmove', this.boundOnTouchMove);
}
/**
* onMouseMove
* @param {MouseEvent | TouchEvent} event
*/
onMouseMove(event) {
var rect = this.canvas.getBoundingClientRect();
var oldMousePos = new Vector2(this.mousePos.x, this.mousePos.y);
this.mousePos.x = event.clientX - rect.left;
this.mousePos.y = event.clientY - rect.top;
//Time since last mouse movement
if (this.mouseTimeStamp !== 0) {
this.mouseElapsedTime = (Date.now() - this.mouseTimeStamp) / 1000;
//console.log('elapsed time: ' + this.mouseElapsedTime);
}
this.mouseTimeStamp = Date.now();
this.mouseVel = this.mousePos
.subtract(oldMousePos)
.scalarDiv(this.mouseElapsedTime);
if (this.selectedObject !== null) {
//Clear text highlight
var sel = window.getSelection
? window.getSelection()
: document.selection;
if (sel) {
if (sel.removeAllRanges) {
sel.removeAllRanges();
} else if (sel.empty) {
sel.empty();
}
}
}
}
/**
* Allows user to add functionality to onMouseMove
* @param {Function} userFunction
*/
setOnMouseMove(userFunction) {
let move = this.onMouseMove.bind(this);
this.canvas.onmousemove = function (event) {
move(event);
userFunction();
};
}
onMouseDown() {
console.log('press');
this.mouseHeld = true;
this.physObjects.forEach((ball) => {
if (ball.position.distance(this.mousePos) < ball.radius) {
this.selectedObject = ball;
this.onObjectPress();
}
});
}
/**
* Allows user to add functionality to onMouseDown
* @param {Function} userFunction
*/
setOnMouseDown(userFunction) {
let down = this.onMouseDown.bind(this);
this.canvas.onmousedown = function () {
down();
userFunction();
};
}
onMouseUp() {
console.log('release');
this.mouseHeld = false;
if (this.selectedObject !== null) {
this.onObjectRelease();
this.selectedObject = null;
}
}
/**
* Allows user to add functionality to onMouseUp
* @param {Function} userFunction
*/
setOnMouseUp(userFunction) {
let up = this.onMouseUp.bind(this);
this.canvas.onmouseup = function () {
up();
userFunction();
};
}
onTouchMove(event) {
var rect = this.canvas.getBoundingClientRect();
var oldMousePos = new Vector2(this.mousePos.x, this.mousePos.y);
this.mousePos.x = event.touches[0].pageX - rect.left;
this.mousePos.y = event.touches[0].pageY - rect.top;
console.log(this.mousePos.x);
//Time since last mouse movement
if (this.mouseTimeStamp !== 0) {
this.mouseElapsedTime = (Date.now() - this.mouseTimeStamp) / 1000;
}
this.mouseTimeStamp = Date.now();
this.mouseVel = this.mousePos
.subtract(oldMousePos)
.scalarDiv(this.mouseElapsedTime);
}
/**
* Allows user to add functionality to onTouchMove
* @param {Function} userFunction
*/
setOnTouchMove(userFunction) {
let move = this.onTouchMove.bind(this);
this.canvas.ontouchmove = function (event) {
move(event);
userFunction();
};
}
onTouchStart(event) {
console.log('press');
this.mouseHeld = true;
var rect = this.canvas.getBoundingClientRect();
this.mousePos.x = event.touches[0].pageX - rect.left;
this.mousePos.y = event.touches[0].pageY - rect.top;
console.log(this.mousePos.y);
this.physObjects.forEach((ball) => {
if (ball.position.distance(this.mousePos) < ball.radius) {
this.selectedObject = ball;
this.onObjectPress();
}
});
}
/**
* Allows user to add functionality to onTouchStart
* @param {Function} userFunction
*/
setOnTouchStart(userFunction) {
let touchStart = this.onTouchStart.bind(this);
this.canvas.ontouchmove = function (event) {
touchStart(event);
userFunction();
};
}
/**
* Sets onObjectPress to the specified function
* @param {Function} userFunction
*/
setOnObjectPress(userFunction) {
this.onObjectPress = userFunction;
}
/**
* Sets onObjectRelease to the specified function
* @param {Function} userFunction
*/
setOnObjectRelease(userFunction) {
this.onObjectRelease = userFunction;
}
/**
* Sets whileObjectHeld to the specified function
* @param {Function} userFunction
*/
setWhileObjectHeld(userFunction) {
this.whileObjectHeld = userFunction;
}
stop() {
this.isStopped = true;
window.removeEventListener('mouseup', this.boundOnMouseUp);
window.removeEventListener('mousedown', this.boundOnMouseDown);
window.removeEventListener('mousemove', this.boundOnMouseMove);
window.removeEventListener('touchstart', this.boundOnTouchStart);
window.removeEventListener('touchend', this.boundOnMouseUp);
window.removeEventListener('touchmove', this.boundOnTouchMove);
}
start() {
requestAnimationFrame(this.runFrame.bind(this));
}
/**
* Run engine frame. Passes itself recursively into requestAnimationFrame.
* @param {DOMHighResTimeStamp} DOMTimeStamp
*/
runFrame(DOMTimeStamp) {
if (this.isStopped) {
this.onStop();
console.log('Engine stopped.');
return;
}
this.onFrame();
if (this.selectedObject !== null) {
this.whileObjectHeld();
}
// Check collisions with other balls
this.physObjects.forEach((ball1) => {
if (ball1.collidesWithObjects) {
this.physObjects.forEach((ball2) => {
if (
ball2.collidesWithObjects &&
!(ball1.isStatic && ball2.isStatic)
) {
var dist = ball1.position.distance(ball2.position);
if (ball1 !== ball2 && dist < ball1.radius + ball2.radius) {
//console.log('Collision');
// Handle overlap
var overlap = (ball1.radius + ball2.radius - dist) / 2;
if (ball1.isStatic) {
ball2.position.x -=
((overlap * 2) / dist) *
(ball1.position.x - ball2.position.x);
ball2.position.y -=
((overlap * 2) / dist) *
(ball1.position.y - ball2.position.y);
} else if (ball2.isStatic) {
ball1.position.x -=
((overlap * 2) / dist) *
(ball2.position.x - ball1.position.x);
ball1.position.y -=
((overlap * 2) / dist) *
(ball2.position.y - ball1.position.y);
} else {
ball1.position.x -=
(overlap / dist) * (ball2.position.x - ball1.position.x);
ball1.position.y -=
(overlap / dist) * (ball2.position.y - ball1.position.y);
ball2.position.x -=
(overlap / dist) * (ball1.position.x - ball2.position.x);
ball2.position.y -=
(overlap / dist) * (ball1.position.y - ball2.position.y);
}
// Distance between centers of the circles
var centerDistance = ball1.position.distance(ball2.position);
// Normal unit vector
var normal = new Vector2(
ball2.position.x - ball1.position.x,
ball2.position.y - ball1.position.y
);
normal = normal.scalarDiv(centerDistance);
// Tangnet unit vector
var tangent = new Vector2(-normal.y, normal.x);
// Get velocities in new coordinates by dotting with the normal and tangent
var v1 = new Vector2(
ball1.velocity.dot(normal),
ball1.velocity.dot(tangent)
);
var v2 = new Vector2(
ball2.velocity.dot(normal),
ball2.velocity.dot(tangent)
);
var m1 = ball2.isStatic ? 0.0 : ball1.mass;
var m2 = ball1.isStatic ? 0.0 : ball2.mass;
// Calculate the new normal velocities using 1D conservation of momentum
var v1x = ((m1 - m2) * v1.x + 2 * m2 * v2.x) / (m1 + m2);
var v2x = ((m2 - m1) * v2.x + 2 * m1 * v1.x) / (m1 + m2);
v1.x = v1x;
v2.x = v2x;
// x and y axes from the perspective of the new coordinates
var xAxis = new Vector2(normal.x, -normal.y);
var yAxis = new Vector2(-tangent.x, tangent.y);
// Update ball velocities
ball1.velocity.x = v1.dot(xAxis);
ball1.velocity.y = v1.dot(yAxis);
ball2.velocity.x = v2.dot(xAxis);
ball2.velocity.y = v2.dot(yAxis);
ball1.onObjectCollison();
ball2.onObjectCollison();
// javidx9 way to Update ball velocities
// ball1.velocity.x = tangent.x * v1.y + normal.x * v1.x;
// ball1.velocity.y = tangent.y * v1.y + normal.y * v1.x;
// ball2.velocity.x = tangent.x * v2.y + normal.x * v2.x;
// ball2.velocity.y = tangent.y * v2.y + normal.y * v2.x;
} // end if
} // end if
}); // end forEach
} // end if
}); // end forEach
// Check collisions with walls (borders of canvas)
this.physObjects.forEach((ball) => {
if (ball.collidesWithWalls) {
if (ball.position.x - ball.radius < 0) {
ball.position.x += ball.radius - ball.position.x;
ball.velocity.x = -ball.velocity.x;
ball.onWallCollision();
} // end if
if (ball.position.x + ball.radius > this.width) {
ball.position.x -= ball.radius - (this.width - ball.position.x);
ball.velocity.x = -ball.velocity.x;
ball.onWallCollision();
} //end if
if (ball.position.y - ball.radius < 0) {
ball.position.y += ball.radius - ball.position.y;
ball.velocity.y = -ball.velocity.y;
ball.onWallCollision();
} //end if
if (ball.position.y + ball.radius > this.height) {
ball.position.y -= ball.radius - (this.height - ball.position.y);
ball.velocity.y = -ball.velocity.y;
ball.onWallCollision();
} //end if
} //end if
}); //end forEach
//Time since last update
if (this.timeStamp !== 0) {
this.elapsedTime = (DOMTimeStamp - this.timeStamp) / 1000;
//console.log('elapsed time: ' + this.elapsedTime);
}
this.timeStamp = DOMTimeStamp;
//Update physics of balls
this.physObjects.forEach((ball) => {
ball.position.x += ball.velocity.x * this.elapsedTime;
ball.position.y += ball.velocity.y * this.elapsedTime;
ball.acceleration.x = ball.drag * -ball.velocity.x;
ball.acceleration.y = ball.drag * -ball.velocity.y;
ball.velocity.x += ball.acceleration.x * this.elapsedTime;
ball.velocity.y +=
(ball.acceleration.y + ball.gravity) * this.elapsedTime;
if (ball.velocity.magnitude < 1) {
ball.velocity = new Vector2(0, 0);
}
});
this.canvas2D.fillStyle = this.backgrndColor;
this.canvas2D.fillRect(0, 0, this.width, this.height);
//Draw the balls
this.physObjects.forEach((ball) => {
ball.draw(this.canvas);
});
requestAnimationFrame(this.runFrame.bind(this));
} //end runFrame()
/**
* Adds another object to the engine
* @param {Ball} ball
*/
add(ball) {
this.physObjects.push(ball);
ball.draw(this.canvas);
}
} //end Engine