我在画布上旋转了我的方块,我想检测它们之间的碰撞,虽然通常的方法显然不起作用。应该怎么做?
正如你可能看到的那样,如果它们碰撞其中一个盒子会变成红色,但如果只有这些提示发生碰撞则没有任何反应。
var canvas,ctx,box1,box2,mouseX,mouseY,intervalo;
function load(){
canvas = document.getElementById('box');
ctx = canvas.getContext('2d');
function box(x,y,width,height,color,angle){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
this.angle = angle;
this.rotateX = x;
this.rotateY = y;
this.drawn = function(){
var rad = this.angle*(Math.PI/180);//Here you should turn degrees into radians by -> *(Math.PI/180);
ctx.translate(this.x + (this.width / 2), this.y + (this.height / 2))//Change screen cordinates to center of object
ctx.rotate(rad);//Rotate canvas
//What you want to rotate:
this.rotateX = (this.width / 2) * (-1);
this.rotateY = (this.height / 2) * (-1);
ctx.fillStyle = this.color;
ctx.fillRect(this.rotateX,this.rotateY,this.width,this.height);
//end
ctx.rotate(rad * (-1));//Unrotate canvas
ctx.translate((this.x + (this.width / 2)) * (-1), (this.y + (this.height / 2)) * (-1));//Change screen cordinates back to normal
}
}
box1 = new box(500,250,50,50,"white",45);
box2 = new box(250,250,50,50,"white",45);
document.onmousemove = mouseMove;
function mouseMove(event) {
event = event || canvas.event
mouseX = event.pageX;
mouseY = event.pageY;
mouseX = mouseX - 11;
mouseY = mouseY - 13;
box2.x = mouseX;
box2.y = mouseY;
}
intervalo = setInterval(animation, 1000/60);
}
function animation(){
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvas.width,canvas.height);
for (var i = 0;i < 2; i++){
//Colision detection that doesn't work:
if (!(box1.x+box1.width < box2.x) &&
!(box2.x+box2.width < box1.x) &&
!(box1.y+box1.height < box2.y) &&
!(box2.y+box2.height < box1.y)) {
console.log("colision");
box2.color = "red";
} else {
box2.color = "white";
}
box1.drawn();
box2.drawn();
}
}
#box {
border: 1px solid black;
border-color: white;
}
#button {
border: none;
background-color: gray;
width: 70;
height: 50;
}
canvas {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
html {
background-color: black;
color: white;
font-family: courier new;
}
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<script src="js/main.js"></script>
</head>
<body onload="load()">
<canvas id="box" width="1330" height="500"></canvas>
<button onclick="play()" id="button">Play</button>
</body>
</html>