Hexworks / mixite

A GUI agnostic hexagonal grid library. Supports a multitude of grid layouts including hexagonal, triangular, rectangular and more.
Apache License 2.0
191 stars 31 forks source link

Provide strict getByPixelCoordinate(x,y) #32

Open timrobertson100 opened 7 years ago

timrobertson100 commented 7 years ago

This is an enhancement request.

The current implementation of getByPixelCoordinate() provides the nearest hexagon when called with a pixel which lies outside the grid but within the distance of one hexagon. It is therefore an approximation. This makes good sense for many applications whereby a user is clicking a screen pixel, and some tolerance is acceptable. There are certain use cases however, such as the binning of points into hexagons which require a guarantee that the coordinate lies within the hexagon.

While this behaviour remains, a workaround for this scenario is proposed as:

  1. Instantiate a grid that is 1 hexagon larger all around than necessary. Should the hexagons be used on multiple adjacent canvases (e.g. on map tiles) whereby the grid is further offset to ensure adjacent hexagons align, then a larger buffer is recommended. Note for flatTop you need to increase by 2 hexagons left and right to achieve 1 complete hexagon.
  2. Offset the coordinates by the buffer size. (e.g. for flat topped hexagons with a buffer of 4 hexagons horizontally (2 left, 2 right) and 2 vertically, the offsetX is 1.5*hexWidth, and the offsetY is 1*hexHeight before calling getByPixelCoordinate(x,y)
  3. Compensate at rendering time by adjusting the vertices of the hexagon by the same offset.

As a quick fix I suggest adding a sentence in the Javadoc for the method as follows:

Note that at the boundaries this is a lenient match. When the pixel provided does not fall within a hexagon on the grid, but is within a close distance of the grid, the nearest hexagon will be returned. Where strict hexagon matching is required, please refer to the workaround offered on https://github.com/Hexworks/hexameter/issues/32

adam-arold commented 7 years ago

Good catch! I'll look into it. Conceptually this method should give you a non-present result for any pixel which is not part of a hexagon so I'll try to implement it like this.

HoldYourWaffle commented 4 years ago

Is this still an issue? The current documentation reads:

@return Maybe with a Hexagon if it is present

Implying that there won't be a result if there is no Hexagon at the specified coordinates.

adam-arold commented 4 years ago

I'm gonna check, but I don't recall making changes to the code.