我有一個程序使用一個簡筆畫和一個正方形的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);