You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
2.0 KiB
53 lines
2.0 KiB
'use strict';
|
|
|
|
/*
|
|
2D Collision detection and performing
|
|
*/
|
|
|
|
class Collision{
|
|
|
|
static ellipseToEllipse(e1, e2){
|
|
|
|
//Colliding angle of ball 1 to ball 2 using arc tan of both x and y differences
|
|
let collisionAngle = Math.atan2((e2.pos.y - e1.pos.y), (e2.pos.x - e1.pos.x));
|
|
|
|
//Converting directions of velocity vector of balls into angles
|
|
let d1 = Math.atan2(e1.vel.y, e1.vel.x);
|
|
let d2 = Math.atan2(e2.vel.y, e2.vel.x);
|
|
|
|
//Ignoring mass effects new velocites are simply magnitude multiplied with value of angle differences
|
|
let newXspeed1 = e1.vel.mag() * Math.cos(d1 - collisionAngle);
|
|
let newYspeed1 = e1.vel.mag() * Math.sin(d1 - collisionAngle);
|
|
let newXspeed2 = e2.vel.mag() * Math.cos(d2 - collisionAngle);
|
|
let newYspeed2 = e2.vel.mag() * Math.sin(d2 - collisionAngle);
|
|
|
|
//According to the principle of linear momentum, kinetic energy stays the same after collision, so velocities are now related to masses
|
|
let finalXspeed1 = ((e1.radius - e2.radius) * newXspeed1 + e2.radius * 2 * newXspeed2) / (e1.radius + e2.radius);
|
|
let finalYspeed1 = newYspeed1;
|
|
let finalXspeed2 = (e1.radius * 2 * newXspeed1 + (e2.radius - e1.radius) * newXspeed2) / (e1.radius + e2.radius);
|
|
let finalYspeed2 = newYspeed2;
|
|
|
|
//Values of collisionAngle
|
|
let cosAngle = Math.cos(collisionAngle);
|
|
let sinAngle = Math.sin(collisionAngle);
|
|
|
|
//To also keep velocites relative to pure collisionAngle, subtract sin*x from cos*x and add sin*y to cos*y because coordSystem has y = 0 on the top
|
|
let u1x = cosAngle * finalXspeed1 - sinAngle * finalYspeed1;
|
|
let u1y = sinAngle * finalXspeed1 + cosAngle * finalYspeed1;
|
|
let u2x = cosAngle * finalXspeed2 - sinAngle * finalYspeed2;
|
|
let u2y = sinAngle * finalXspeed2 + cosAngle * finalYspeed2;
|
|
|
|
//Set new velocities to both balls
|
|
e1.vel.x = u1x;
|
|
e1.vel.y = u1y;
|
|
e2.vel.x = u2x;
|
|
e2.vel.y = u2y;
|
|
|
|
//Move balls one vx/vy forward to avoid double inverting collision detection
|
|
e1.pos.x += e1.vel.x;
|
|
e1.pos.y += e1.vel.y;
|
|
e2.pos.x += e2.vel.x;
|
|
e2.pos.y += e2.vel.y;
|
|
}
|
|
|
|
} |