我在使用这种碰撞检测算法时遇到了很大的问题。我了解它是如何工作的,但我不知道如何在我的代码中实现它,即使我已经看过很多关于它的教程。此代码段中当前没有碰撞检测代码。这是演示:
var ctx = document.getElementById('canvas').getContext("2d");
var square = {
x:150,
y:100,
width:100,
height:100
};
var triangle = {
x:300,
y:100,
width:100,
height:100
};
function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
//Draw the square
ctx.strokeRect(square.x,square.y,square.width, square.height);
//Draw the triangle
ctx.beginPath();
ctx.moveTo(triangle.x+triangle.width/2,triangle.y);
ctx.lineTo(triangle.x + triangle.width, triangle.y + triangle.height);
ctx.lineTo(triangle.x, triangle.y + triangle.height);
ctx.closePath();
ctx.stroke();
requestAnimationFrame(draw);
}
draw();
document.body.addEventListener("mousemove", function(e) {
square.x = e.clientX;
square.y = e.clientY;
});
canvas {
border:1px solid black;
}
<canvas id="canvas" width="600" height="600"></canvas>