简体   繁体   English

矩形和圆形解决碰撞

[英]Rectangle and circle resolve collision

How can I change the dy of the ball if it touches the top and bottom of the block? 如果球触及方块的顶部和底部,如何改变球的dy? Now it just gets a wobble effect and gets trapped inside of the block when it hits the top or bottom. 现在,它只是具有摆动效果,并且在碰到顶部或底部时会陷入块内。 Here is my Jsfiddle: https://jsfiddle.net/6qh70wdo/ 这是我的Jsfiddle: https ://jsfiddle.net/6qh70wdo/

if (ball.x - ball.radius < block.x + block.w &&
    ball.x + ball.radius > block.x &&
    ball.y - ball.radius < block.y + block.h &&
    ball.y + ball.radius > block.y) {
    ball.dx  = -ball.dx;
}

I would break it up into two sections. 我将其分为两部分。 First detect if it is being hit and then worry about where it's hitting. 首先检测它是否被击中,然后再担心它在哪里被击中。 I think you could do something like this: 我认为您可以执行以下操作:

var bool = ball.x - ball.radius < block.x + block.w &&
    ball.x + ball.radius > block.x &&
    ball.y - ball.radius < block.y + block.h &&
    ball.y + ball.radius > block.y) {
    ball.dx  = -ball.dx;

if(bool) // if true, meaning a hit, find which direction.
    if(ball.x - ball.radius < block.x + block.w || ball.x + ball.radius > block.x){
        ball.dx = -ball.dx; //hit detected on left/right...change left/right direction
    }else{
        ball.dy = -ball.dy; //hit detected on top/bottom...change top/bottom direction
    }
}

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

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