Answers:
如果(x,y)
是矩形的中心,则(px,py)
可以通过以下方式计算从点到矩形边界的平方距离:
dx = max(abs(px - x) - width / 2, 0);
dy = max(abs(py - y) - height / 2, 0);
return dx * dx + dy * dy;
如果该平方距离为零,则表示该点触摸矩形或位于矩形内部。
我假设您的矩形是Axis-Aligned。
您只需要将点“夹紧”到矩形中,然后计算到夹紧点的距离即可。
点=(px,py),矩形=(rx,ry,rwidth,高度)//(左上角,尺寸)
function pointRectDist (px, py, rx, ry, rwidth, rheight)
{
var cx = Math.max(Math.min(px, rx+rwidth ), rx);
var cy = Math.max(Math.min(py, ry+rheight), ry);
return Math.sqrt( (px-cx)*(px-cx) + (py-cy)*(py-cy) );
}
如果要计算从点到矩形边缘的距离,则使用矩形创建的九个区域中的每个区域可能是最快的方法:
function pointRectangleDistance(x, y, x1, y1, x2, y2) {
var dx, dy;
if (x < x1) {
dx = x1 - x;
if (y < y1) {
dy = y1 - y;
return Math.sqrt(dx * dx + dy * dy);
}
else if (y > y2) {
dy = y - y2;
return Math.sqrt(dx * dx + dy * dy);
}
else {
return dx;
}
}
else if (x > x2) {
dx = x - x2;
if (y < y1) {
dy = y1 - y;
return Math.sqrt(dx * dx + dy * dy);
}
else if (y > y2) {
dy = y - y2;
return Math.sqrt(dx * dx + dy * dy);
}
else {
return dx;
}
}
else {
if (y < y1) {
return y1 - y;
}
else if (y > y2) {
return y - y2;
}
else {
return 0.0; // inside the rectangle or on the edge
}
}
}
[根据评论修改答案]
如果要查看下图的灰色矩形是否在10个单位内,请检查该点是否位于
inside=false;
bluerect.x=oldrect.x-10;
bluerect.y=oldrect.y;
bluerect.width=oldrect.width;
bluerect.height=oldrect.height+20;
if( point.x >=bluerect && point.x <=redrect.x+bluerect.width &&
point.y >=bluerect && point.y <=redrect.y+bluerect.height){
//now point is side the blue rectangle
inside=true;
}
redrect.x=oldrect.x;
redrect.y=oldrect.y-10;
redrect.width=oldrect.width+20;
redrect.height=oldrect.height;
if( point.x >=redrect&& point.x <=redrect.x+redrect.width &&
point.y >=redrect&& point.y <=redrect.y+redrect.height){
//now point is side the redrectangle
inside=true;
}
d1= distance(point, new point(oldrect.x, oldrect.y)) //calculate distance between point and (oldrect.x, oldrect.y)
d2= distance(point, new point(oldrect.x+10, oldrect.y))
d3= distance(point, new point(oldrect.x, oldrect.y+10))
d4= distance(point, new point(oldrect.x+10, oldrect.y+10))
if (d1 < 10 || d2 <10 || d3 < 10 || d4 <10){
inside=true;
}
//inside is now true if the point is within 10 units of rectangle
这种方法有点不雅致。在stackoverflow上记录了一种类似的方法,该方法避免了必须使用矩形对称性来测试所有4个角的情况
您可以使用如下形式: