简体   繁体   中英

detecting collisions on the canvas

im trying to make a game where collisions happen between the protagonist and the antagonist. I cant get the collision to work though, i've tried using the x and y position then the x and y positions plus the width and the height of the protagonist and the antagonist

 var canvas = document.getElementById('canvas'); var PX = 10; var PY = 10; var PW = 10; var PH = 10; var P = PX + PY; var EX1 = 100; var EY1 = 100; var EW1 = 10; var EH1 = 10; var E1 = EX1 + EY1; window.addEventListener("keydown", charMove); window.addEventListener("keyup", charMove); window.addEventListener("keypress", charMove); window.onload = function() { context = canvas.getContext("2d"); canvas.style.background = "black"; var framesPerSecond = 30; setInterval(function() { draw(); move(); }, 1000/framesPerSecond); } function draw() { //EX context.fillRect(PosX, PosY, width, height); //draws protagonist context.beginPath(); context.clearRect(0, 0, canvas.width, canvas.height); context.fillStyle = "blue" context.fillRect(PX, PY, PW, PH); context.stroke(); context.closePath(); //draws antagonist(s) context.beginPath(); context.fillStlyle = "red"; context.fillRect(EX1, EY1, EW1, EH1); context.stroke(); context.closePath(); } function move() { } function charMove(){ var x = event.which || event.keyCode; if(x == 37){ PX -= 1; } if(x == 38){ PY -= 1; } if(x == 39){ PX += 1; } if(x == 40){ PY += 1; } } //detect collision setInterval(function() { if(PX > EX1 || PX + PW < EX1 + EW1 && PY + PH > EY1 + EH1 || PY + PH < EY1 + EH1){ window.alert("collision"); } }, 1); 
 <html> <head> </head> <body> <canvas width="500px" height="500px" id="canvas" class="canvas"> </body> </html> 

Your formula for collision is wrong.

This problem is called Axis Aligned Bounding Box collision.

Two AABBs collide if their projections to each axis collide. In your 2-dimensinal case you have to consider the horizontal and vertical projections.

The projections are segments of 1-d space. Collision for those is very easy: if the start or the end of a segment is on the other they collide. Formally start2 <= start1 <= end2 or start2 <= end1 <= end2

In code:

intersects([p.x, p.x + p.width], [e.x, e.x + e.width]) && intersects([p.y, p.y + p.height], [e.y, e.y + e.height])

where

function intersects(seg1, seg2) {
    return contains(seg1, seg2[0]) || contains(seg1, seg2[1])
}
function contains(segment, point) {
    return segment[0] <= point && point <= segment[1]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM