Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

91
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda