1if (rect1.x < rect2.x + rect2.width &&
2 rect1.x + rect1.width > rect2.x &&
3 rect1.y < rect2.y + rect2.height &&
4 rect1.y + rect1.height > rect2.y) {
5 // collision detected!
6}
1function checkCollisions(x1, y1, w1, h1, x2, y2, w2, h2){
2 if (x1 + w1 >= x2 && x1 + w1 <= x2 + w2 && y1 + h1 >= y2 && y1 + h1 <= y2 + h2) {
3 return true;
4 } else if (x1 >= x2 && x1 <= x2 + w2 && y1 >= y2 && y1 <= y2 + h2) {
5 return true;
6 } else {
7 return false;
8 }
9}
1/*
2 You should call the function resolveCollsion, when a collision between two
3 circles is detected.
4*/
5
6function rotate(velocity, angle) {
7 const rotatedVelocities = {
8 x: velocity.x * Math.cos(angle) - velocity.y * Math.sin(angle),
9 y: velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
10 }
11
12 return rotatedVelocities;
13}
14
15function resolveCollision(particle, otherParticle) {
16 /*
17 the particles passed as parameters should be objects with
18 x and y position,
19 a velocity object with x and y values,
20 a mass value
21 as attributes
22 example of a class:
23
24 function Circle() {
25 this.x = x;
26 this.y = y;
27 this.velocity = {
28 x: 5,
29 y: 5
30 };
31 this.mass = 2;
32
33 }
34 */
35 const xVelocityDiff = particle.velocity.x - otherParticle.velocity.x;
36 const yVelocityDiff = particle.velocity.y - otherParticle.velocity.y;
37
38 const xDist = otherParticle.x - particle.x;
39 const yDist = otherParticle.y - particle.y;
40
41 if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
42 const angle = -Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);
43
44 const m1 = particle.mass;
45 const m2 = otherParticle.mass;
46
47 const u1 = rotate(particle.velocity, angle);
48 const u2 = rotate(otherParticle.velocity, angle);
49
50 const v1 = { x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2), y: u1.y };
51 const v2 = { x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2), y: u2.y };
52
53 const vFinal1 = rotate(v1, -angle);
54 const vFinal2 = rotate(v2, -angle);
55
56 particle.velocity.x = vFinal1.x;
57 particle.velocity.y = vFinal1.y;
58
59 otherParticle.velocity.x = vFinal2.x;
60 otherParticle.velocity.y = vFinal2.y;
61 }
62}
63
64/*
65 source:
66 https://youtu.be/789weryntzM
67*/