2017-11-13 3 views
0

ボールがブロックの上部と下部に接触すると、ボールのdyをどのように変更できますか?これで、ウォブル効果が得られ、ブロックの上部または下部に当たるとブロックの内側に閉じ込められます。ここ は私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; 
} 

答えて

0

私は2つのセクションに分割してしまいます。まず、ヒットしているかどうかを検出し、ヒットしている場所を心配します。あなたは次のようなことをすることができると思います:

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