Advertisement

Which center of rectangle is closest to a Point

Started by December 14, 2019 01:29 PM
4 comments, last by jason30 4 years, 10 months ago

Hi everyone,
would like to know the formula for determining which center of rectangle is closest to a Point. Known values are cartesian x,y of all the rectangles, point, and screen x,y as well as width/heights of screen space and rectangles.

The red dot can be any arbitrary Point, or x,y of mouse

For each rectangle:

  • The center is the average of two opposite points, or the origin plus half of the extents.
  • Calculate the vector difference between the center and your point by subtracting their coordinates.
  • The square of the length of the vector difference is d.x * d.x + d.y *d.y. This is therefore the square of the distance between the point and the center of the rectangle.
  • The center with the smallest squared distance to the point is the center that's nearest to the point.
Advertisement
  1. Calculate the center of each rectangle. centerX = cartesianX + width/2
  2. Loop through the rectangles
  3. Calculate the distance from the point to the center. https://www.purplemath.com/modules/distform.htm
  4. Store the best distance and the rectangle.

Hello to all my stalkers.

Worked perfectly.

      var w = this.map.tilewidth/2;
      var h = this.map.tileheight/2;
      var mx = e.src.pageX;
      var my = e.src.pageY;
      var nodes = document.elementsFromPoint(mx,my);
        nodes.forEach(n =>{
          var coordsA = n.getBoundingClientRect();
          n.centerX = coordsA.left+ w;
          n.centerY = coordsA.top + h;
          n.distToPointX = Math.abs(n.centerX-mx);
          n.distToPointY = Math.abs(n.centerY-my);
          n.dist = n.distToPointX*n.distToPointX + n.distToPointY*n.distToPointY;
        })
        nodes.sort(function(a, b) {
         return a.dist == b.dist
             ? 0
             : (a.dist > b.dist ? 1 : -1);
        });
        console.log("rectangle that got clicked", nodes.shift())


Thank you both ! :D

This topic is closed to new replies.

Advertisement