简体   繁体   English

如何从侧边实现球和正方形之间的碰撞检测?

[英]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.下面的代码检测到两个物体之间的碰撞,但它只改变球的 y 轴方向。有人可以帮助如何实现侧向碰撞吗?比如如果它击中侧边,球的方向应该改变仅在其 x 轴上。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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