2017-06-01 49 views
0

我確定了一個碰撞檢測系統,但現在我試圖做一個系統,使得當調用函數時,參數中的項不能互相觸及。我對JavaScript很陌生,它的第一個語言真的很想學習。矩形繪製的方式是讓x和y位於矩形的中間,而不是位於矩形的左上角。我製作的系統技術上的作品,但只有當它是一個完美的廣場,由於某種原因矩形是越野車,我不知道。即使它是一個完美的正方形,它似乎笨重,真的很不好,這是我習慣的,這是code.org的item1.collide(item2);這完美,完全如何我想要的,但我不能找到背後的代碼。順便說一句,我正在使用p5.js。我該如何改進JavaScript中的碰撞攔截系統?

這裏是如何我畫我的矩形:

rect(this.x-this.width/2,this.y-this.height/2,this.width,this.height); 

這裏是blockCollision函數我目前有:

function blockCollision(a,b){ 
    if(a.x+a.width/2 > b.x-b.width/2 && 
    a.x-a.width/2 < b.x+b.width/2 && 
    a.y-a.height/2 < b.y+b.height/2 && 
    a.y+a.height/2 > b.y-b.height/2) { 
     if(a.x<b.x-b.width/2) a.x=b.x-b.width/2-a.width/2; 
     if(a.x>b.x+b.width/2) a.x=b.x+b.width/2+a.width/2; 
     if(a.y<b.x-b.height/2) a.y=b.x-b.height/2-a.height/2; 
     if(a.y>b.x+b.height/2) a.y=b.x+b.height/2+a.height/2; 
    } 
} 

而且,這裏是整個代碼下載,如果有幫助: https://drive.google.com/open?id=0B-F5CHOIQvvGVlR3Njd1M1NLS1E

回答

0

我認爲通過「塊碰撞」,你的意思是你想在碰撞的「相反」方向上移動一個塊,這樣碰撞不會發生。

你需要做的基本上是確定碰撞的方向是什麼(上/下/左/右),和移動違規街區:

function blockCollision(a, b) { 
    // Assuming (0, 0) is the top left corner 
    const aTop = a.y - a.height/2; 
    const aBottom = a.y + a.height/2; 
    const aLeft = a.x - a.width/2; 
    const aRight = a.x + a.width/2; 

    const bTop = b.y - b.height/2; 
    const bBottom = b.y + b.height/2; 
    const bLeft = b.x - b.width/2; 
    const bRight = b.x + b.width/2; 

    const collisions = []; 

    if (aTop <= bTop && aBottom >= bTop) { 
    // a is above B, potential collision 

    if (aLeft <= bRight && bLeft <= aRight) { 
     // Prevent collision, push a to the top 
     a.y = bTop - (a.height/2) - 1; 
    } 
    } 

    if (aBottom >= bBottom && aTop <= bBottom) { 
    // a is below B, potential collision 

    if (aLeft <= bRight && bLeft <= aRight) { 
     // Prevent collision 
     a.y = bBottom + (a.height/2) + 1; 
    } 
    } 

    if (aLeft <= bLeft && aRight >= bLeft) { 
    // a is left of B, potential collision 

    if (aTop <= bBottom && bTop <= aBottom) { 
     // Prevent collision, push a to the left 
     a.x = bLeft - (a.width/2) - 1; 
    } 
    } 

    if (aRight >= bRight && aLeft <= bRight) { 
    // a is right of B, potential collision 

    if (aTop <= bBottom && bTop <= aBottom) { 
     // Prevent collision, push a to the right 
     a.x = bRight + (a.width/2) + 1; 
    } 
    } 
} 

codepen example