簡體   English   中英

矩形和圓形解決碰撞

[英]Rectangle and circle resolve collision

如果球觸及方塊的頂部和底部,如何改變球的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;
}

我將其分為兩部分。 首先檢測它是否被擊中,然后再擔心它在哪里被擊中。 我認為您可以執行以下操作:

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