How can I change the dy of the ball if it touches the top and bottom of the block? 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/
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
}
}
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.