0
votes

the below code detects the collision between two objects but it only changes direction only along the y-axis of the ball.can someone please help as to how to implement the sideways collision ?like if it hits on the side edges the ball direction should change on its x-axis only.

bricks.forEach(column=>{
        column.forEach(brick=>{
            if (brick.visible){
                if(ball.x-ball.size>brick.x && ball.x+ball.size<brick.x+brick.w && ball.y+ball.size>brick.y && ball.y-ball.size<brick.y+brick.h)
                    {
                        ball.dy*=-1;
                        brick.visible=false;
                    }
            }
        })
    })
1

1 Answers

0
votes

i added a few things but it gives poor result as in its handling the bounce from the edges .can somes give some recommendations on a better way to handle collsion?

 bricks.forEach(column=>{
        column.forEach(brick=>{
            if (brick.visible){
                if(ball.x-ball.size>brick.x && ball.x+ball.size<brick.x+brick.w && ball.y+ball.size+ball.speed>brick.y && ball.y-ball.size+ball.speed<brick.y+brick.h)
                    {
                        ball.dy*=-1;
                        brick.visible=false;
                    }
                if(ball.y-ball.size>brick.y && ball.y+ball.size<brick.y+brick.h && ball.x+ball.size+ball.speed>brick.x && ball.x-ball.size+ball.speed<brick.x+brick.w)
                    {
                        ball.dx*=-1;
                        brick.visible=false;
                    }
            }
        })
    })
}