I'm trying to recreate physics and got 2 live rectangle bodies bouncing on each other, however, when I added more, they started to phase in on each other, here's what that looks like. Given that a body can be either static or live, static blocks do not move:
import { RigidBodyProps } from '../index';
export class Collision {
static Start(gravity: number, target: RigidBodyProps, index: number, bodies: RigidBodyProps[]) {
// Optimized collision search
for (let i = index + 1; i < bodies.length; i++) {
const targetCollides = checkCollision(target, bodies[i]);
const bodyCollides = checkCollision(bodies[i], target);
if (targetCollides !== 'none') {
const restitution = 0.75;
const targetMomentum = Math.abs(-target.speed.y * restitution + gravity);
const bodyMomentum = Math.abs(-bodies[i].speed.y * restitution + gravity);
if (targetCollides === 'bottom') return target.speed.y = targetMomentum;
if (targetCollides === 'top') return target.speed.y = -targetMomentum;
}
}
}
}
// Returns the side that was collided the most
function checkCollision(b1: RigidBodyProps, b2: RigidBodyProps) {
const dx = (b1.x + b1.w / 2) - (b2.x + b2.w / 2);
const dy = (b1.y + b1.h / 2) - (b2.y + b2.h / 2);
const width = (b1.w + b2.w) / 2;
const height = (b1.h + b2.h) / 2;
const crossWidth = width * dy;
const crossHeight = height * dx;
if (Math.abs(dx) <= width && Math.abs(dy) <= height) {
if (crossWidth > crossHeight) {
return (crossWidth > -crossHeight) ? 'bottom' : 'left';
}
return (crossWidth > -crossHeight) ? 'right' : 'top';
}
return 'none'
}