Skip to content

Commit

Permalink
fix: Misalignment of the hittest area of PolygonHitbox (#2930)
Browse files Browse the repository at this point in the history
When performing a pointer hit test using PolygonHitbox, there may be a
discrepancy between the expected range and the range in which the hit
test succeeds. If the polygon shape has an offset at the top left, the
hit test will behave as if there is no offset.

Investigation revealed that the cause was in the calculation of
containsLocalPoint() in the PolygonComponent. The unnecessary offset
calculation was removed, and the hit test is now performed in the
expected range.


Closes #2758

---------

Co-authored-by: Lukas Klingsbo <me@lukas.fyi>
  • Loading branch information
organic-nailer and spydon committed Dec 17, 2023
1 parent 576fac3 commit dbdb137
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
5 changes: 2 additions & 3 deletions packages/flame/lib/src/geometry/polygon_component.dart
Expand Up @@ -231,9 +231,8 @@ class PolygonComponent extends ShapeComponent {
}
for (var i = 0; i < _vertices.length; i++) {
final edge = getEdge(i, vertices: vertices);
final isOutside = (edge.to.x - edge.from.x) *
(point.y - edge.from.y + _topLeft.y) -
(point.x - edge.from.x + _topLeft.x) * (edge.to.y - edge.from.y) >
final isOutside = (edge.to.x - edge.from.x) * (point.y - edge.from.y) -
(point.x - edge.from.x) * (edge.to.y - edge.from.y) >
0;
if (isOutside) {
return false;
Expand Down
13 changes: 13 additions & 0 deletions packages/flame/test/components/shape_component_test.dart
Expand Up @@ -43,6 +43,19 @@ void main() {
);
});

test('polygon contains point in local', () {
final polygon = PolygonComponent(
[
Vector2(0.5, 0.5),
Vector2(0.5, 1.5),
Vector2(1.5, 1.5),
Vector2(1.5, 0.5),
],
);
expect(polygon.containsLocalPoint(Vector2(0.25, 0.25)), isFalse);
expect(polygon.containsLocalPoint(Vector2(0.75, 0.75)), isTrue);
});

test('rotated circle does not contain point', () {
final component = CircleComponent(
radius: 1.0,
Expand Down

0 comments on commit dbdb137

Please sign in to comment.