简体   繁体   中英

how to implent collision detection between ball and square from the side edges?

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;
                    }
            }
        })
    })

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;
                    }
            }
        })
    })
}

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