如上图所示,假设有一条从中心发出的光线在矩形边缘碰撞。所以我想计算它碰撞的点,这样我就可以计算出边缘点和中心点之间的距离。
答案 0 :(得分:1)
让中心为(0,0),光线角度为phi
。伪代码:
c = Cos(phi)
s = Sin(phi)
if Width * Abs(s) < Height * Abs(c) then
x = Sign(c) * Width / 2
y = Tan(phi) * x
else
y = Sign(s) * Height / 2
x = CoTan(phi) * y
答案 1 :(得分:0)
我终于构建了一个函数来查找矩形边缘点的坐标。
function mine(rect,angle){
/* rect is object like this {x:number,y:number,width:number,height:number} */
/* angle is an angle(number) between -Math.PI and Math.PI (in radians) */
if(angle==0){
return{
x:rect.x+rect.width,
y:rect.y+rect.height/2
}
}
/* cp is the center point of the rectangle */
var cp = {
x:rect.x + rect.width/2,
y:rect.y + rect.height/2
};
/*dp is the point of the top right diagonal of the rectangle*/
var dp = {
x:rect.x + rect.width,
y:rect.y
}
var dx = dp.x - cp.x; //distanceX between dp and cp
var dy = dp.y - cp.y; //distanceY between dp and cp
/* calculate the angle of diagonal then abs the angle*/
var diagonalAngle = Math.abs(Math.atan2(dy,dx)); // now we can know from which side the edgePoint is
var distanceX;
var distanceY;
var signX; //a vector
var signY = Math.abs(angle) / angle; //a vector
angle = Math.abs(angle);
if(angle<=Math.PI/2){ //that means that the edge point is somewhere on the half right side of the rectangle
signX = 1;
if(angle<diagonalAngle){ //the edge point is on the right side of the rectangle
distanceX = rect.width/2; // this number is the adjacent of the right triangle
var distance = distanceX/Math.cos(angle); // this number is the hypotenuse width of the right triangle. it is calulated using: cos(angle) = opposite / hypothenuse then hyp = opposite / cos(angle)
distanceY = Math.sqrt(distance*distance - distanceX*distanceX); // theorem of pythagoras
}
else{ //the edge point is on the top or the bottom of the rectangle
distanceY = rect.height/2;
var distance = distanceY/Math.sin(angle); // this number is the hypotenuse width of the right triangle. it is calulated using: sin(angle) = opposite / hypothenuse then hyp = opposite / sin(angle)
distanceX = Math.sqrt(distance*distance - distanceY*distanceY);
}
}
else{ //that means that the edge point is somewhere on the half left side of the rectangle
signX = -1;
var angle2 = Math.PI - angle;
if(angle2<diagonalAngle){//the edge point is on the left side of the rectangle
distanceX = rect.width/2;
var distance = distanceX/Math.cos(angle);
distanceY = Math.sqrt(distance*distance - distanceX*distanceX);
}
else{// the edge point is somewhere on the top or on the bottom
distanceY = rect.height/2;
var distance = distanceY/Math.sin(angle);
distanceX = Math.sqrt(distance*distance - distanceY*distanceY);
}
}
return {
x:cp.x+distanceX*signX,
y:cp.y+distanceY*signY
};
/*By ABOUD*/
}
我测试了我的函数,如果您需要了解它是如何工作的,请访问 my page 并查看源代码。