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

101
Views
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 answers
Answer question

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 Report
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!