2017-04-26 35 views
-1

我有一個程序使用一個簡筆畫和一個正方形的PNG圖片文件。棒圖有能力在屏幕上移動。現在,當棒圖進入廣場時,我試圖在PNG圖片與廣場相撞時,讓程序將isOverlap變量記錄到控制檯。但是,我遇到麻煩並想知道如何解決這個問題?我對我的JavaScript文件的代碼如下,我對碰撞檢測代碼,但它似乎沒有正常工作:從我的答案檢測PNG圖片和矩形之間的衝突JavaScript

var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 

var width = 40 
var height = 40; 
var x2 = Math.round(Math.random() * (canvas.width - width)) + 1; 
var y2 = Math.round(Math.random() * (canvas.height - height)) + 1; 

ctx.fillStyle = "blue"; 
ctx.fillRect(x2, y2, width, height); 


var image = new Image(); 
image.src = "person.png"; 

var imgWidth = 100; 
var imgHeight = 100; 
var x1 = Math.round(Math.random() * (canvas.width - imgWidth)) + 1; 
var y1 = Math.round(Math.random() * (canvas.height - imgHeight)) + 1; 

function drawPlayer() 
{ 
    ctx.drawImage(image, x1, y1, imgWidth, imgHeight); 
} 

function clearPlayer() 
{ 
    ctx.clearRect(x1, y1, imgWidth, imgHeight); 
} 

drawPlayer(); 

function detectCollision() 
{ 
    var top1 = y1; 
    var bottom1 = y1 + imgHeight; 
    var left1 = x1; 
    var right1 = x1 + imgWidth; 

    var top2 = y2; 
    var bottom2 = y2 + height; 
    var left2 = x2; 
    var right2 = x2 + width; 

    var isOverlap; 

    if ((left1 > right2) || (right1 < left2) || (top1 > bottom2) || (bottom1 < top2)) 
    { 
     isOverlap = false; 
    } 
    else 
    { 
     isOverlap = true; 
    } 

    console.log("Overlap = " + isOverlap); 
} 

detectCollision(); 

document.addEventListener('keydown', handleKeydown); 

回答

0

摘錄了類似的問題...

那麼我們如何檢測碰撞?如果我們正在使用矩形,它非常簡單,它是 。我們只是確定一個對象的任何角落是否在另一個對象內部爲 。那麼我們該怎麼做?基本上,我們看到它們是否在X和Y軸上相交。

取兩個長方形:A和B.兩者都有四個邊:頂部,左邊,右邊, 和底部。頂部和底部的邊緣是Y值,邊緣左邊 右邊是X值。兩個矩形相交,如果任何 以下的爲真:

(
    A.left < B.left < A.right 
    OR A.left < B.right < A.right 
) AND (
    A.top < B.top < A.bottom 
    OR A.top < B.bottom < A.bottom 
) 

比較,爲您的碰撞檢測,你應該看到,你已經忽略了幾種可能性。調整你的if/else語句來模仿這個邏輯應該可以做到。

原來的答覆:How can I create the detection for this javascript program of mine?

此外,還要確保你不斷地重新繪製和碰撞檢測。您可以在動畫循環中執行此操作,也可以在handleKeydown函數中執行此操作。