Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
Handle bouncing after collision Javascript

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'
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!