点对点矩形测试

4 javascript

我有这个矩阵

/// as if the create a rectangle
int [][] loc = {
  {5, 15},//(x1, y1)
  {5, 30}, // (x1, y2)
  {20, 15},// (x2, y1)
  {20, 30}, // (x2, y2)
}

// this are the point that i want to check if they are in the rectangular range or not
int [] [] point = {
  {6, 16}, //(x, y)
  {3, 17}, //(x, y)
} 
Run Code Online (Sandbox Code Playgroud)

我希望我的方法可以采取点,并通过使用x1<x<x2和搜索是否在loc范围内 y1<y<y2

sch*_*der 14

点(x,y)位于矩形(x1,y1) - (x2,y2)内

(x1 <= x <= x2)(y1 <= y <= y2)

你的代码应该是这样的(这实际上是C代码,但JavaScript不应该有太大的不同):

 x1 = loc[0][0];
 x2 = loc[2][0];
 y1 = loc[0][1];
 y2 = loc[2][1];
 for (int i = 0; i < num_points; i++) {
   if ((x1 <= point[i][0]) && (point[i][0] <= x2) && 
       (y1 <= point[i][1]) && (point[i][1] <= y2)) {
     // This point is inside the rectangle - insert code here
   } else {
     // This point is not inside the rectangle - insert code here
   }
 }
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于(x1 <= x2)和(y1 <= y2),因此您可能确保使用此代替上面的前四行:

x1 = Math.Min(loc[0][0], loc[2][0]);
x2 = Math.Max(loc[0][0], loc[2][0]);
y1 = Math.Min(loc[0][1], loc[2][1]);
y2 = Math.Max(loc[0][1], loc[2][1]);
Run Code Online (Sandbox Code Playgroud)

  • 我不认为"a <b <c"是一个正确的JS构造(这太糟糕了,因为它会很酷).我尝试使用编写的算法,它给出了误报.然后我只是尝试在我的Chrome控制台中输入"1 <= 100 <= 50",它说'是'.它正在评估第一个表达式(1 <= 100),然后第二个变为'true <= 50',它也变为'true'.唉,你必须更详细地进行范围检查:(lo <= x)&&(x <= hi). (4认同)

Ide*_*ram 6

虽然这个问题得到了广泛的回答,但我想分享我的一段代码,因为它看起来更直观,看起来更像我在高中时的数学.以防万一由于家庭工作人们看起来这个问题:)

function between(min, p, max){
  result = false;

  if ( min < max ){
    if ( p > min && p < max ){
      result = true;
    }
  }

  if ( min > max ){
    if ( p > max && p < min){
      result = true
    }
  }

  if ( p == min || p == max ){
    result = true;
  }

  return result;
}

function point_in_rectagnle( x, y, left, top, right, bottom){
  result = false;

  if ( between(left,x,right) && between(top,y,bottom ) ){
    result = true;
  }
  return result;
}
Run Code Online (Sandbox Code Playgroud)


kri*_*spy 6

问题中的代码是 Java 或 C 或其他一些用 {} 定义数组文字的语言,但由于标记是 Javascript 并且这显示在 Google for Javascript 上,这是在 JS 中进行点矩形交集的合理方法。

function pointRectangleIntersection(p, r) {
    return p.x > r.x1 && p.x < r.x2 && p.y > r.y1 && p.y < r.y2;
}

var point = {x: 1, y: 2};
var rectangle = {x1: 0, x2: 10, y1: 1, y2: 7};
pointRectangleIntersection(point, rectangle);
Run Code Online (Sandbox Code Playgroud)

作为评价,改变提及>>=和/或<<=做的交点,其中包括该矩形边界。