简体   繁体   中英

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM