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

102
Visualizações
Javascript collision detection issue

I have a class with this collisionDetection method:

wallCollisionDetection(){
    if((this.position.x >= canvasWidth-this.radius) || (this.position.x <= this.radius) ){
        this.speed.x = -this.speed.x
    }
    
    if((this.position.y >= canvasHeight-this.radius) || (this.position.y <= this.rafius) ){
        this.speed.y = -this.speed.y
    }
}

Simple enough and it works. From time to time (rarely but still), when the particle hits a vertical wall, it tends to just move vertically, stuck to that wall. Same, when it hits a horizontal wall (then it tends to only move horizontally).

As a reference, if I generate 200 particles and let them move randomly for 5 minutes, an average 2 of them will be stuck in one direction.

I think this code sample should be enough since there is no error thrown. So I believe I'm just missing some extra condition in that method. But if you consider you need more, just ask for it.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Ok, scunliffe showed me the way. It seems that when a particle goes over the boundary, it remains stuck in an infinite "if" loop.

So here is how it solved it (basically, I just set the position to its maximum/minimum allowed value so that the loop doesn't happen):

wallCollisionDetection(){

    if(this.position.x > canvasWidth-this.radius){
        this.position.x = canvasWidth-this.radius;
        this.speed.x = -this.speed.x
    }
    else if(this.position.x < this.radius){
        this.position.x = this.radius
        this.speed.x = -this.speed.x
    }

    if(this.position.y > canvasHeight-this.radius ){
        this.position.y = canvasHeight-this.radius;
        this.speed.y = -this.speed.y
    }
    else if(this.position.y < this.radius){
        this.position.y = this.radius;
        this.speed.y = -this.speed.y
    }
}

Not pretty but it works. Thanks!

about 4 years ago · Juan Pablo Isaza Relatório
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