Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda