Skip to content

Add regular constructors to PolygonComponent and PolygonHitbox #3890

@TRI99ERED

Description

@TRI99ERED

Problem to solve

This proposal aims to improve the classes creating polygons with a direct way to create a regular polygon. Especially relevant for PolygonHitbox, because it only works normally with convex polygons and regular polygons are convex.

Proposal

Feature Request: Add PolygonComponent.regular and PolygonHitbox.regular constructors

Summary

Add convenience constructors to create regular convex polygons (e.g., triangles, pentagons, hexagons) by specifying the number of sides and radius, instead of manually providing a list of vertices.

Use Case

Currently, creating a regular polygon (like a hexagon or octagon) requires manually calculating and providing all vertices:

// Current approach - verbose
final vertices = List.generate(6, (i) {
  final angle = 2 * pi * i / 6;
  return Vector2(100 * cos(angle), 100 * sin(angle));
});
PolygonComponent(vertices);

This feature would allow a much simpler API:

// Proposed API
PolygonComponent.regular(sides: 6, radius: 100);
PolygonHitbox.regular(sides: 6, radius: 100);

Proposed API

PolygonComponent.regular

PolygonComponent.regular({
  required int sides,
  required double radius,
  Vector2? position,
  Vector2? size,
  Vector2? scale,
  double? angle,
  Anchor? anchor,
  Iterable<Component>? children,
  int? priority,
  Paint? paint,
  List<Paint>? paintLayers,
  ComponentKey? key,
  bool? shrinkToBounds,
})
  • sides: Number of sides (must be > 2)
  • radius: Distance from center to each vertex
  • shrinkToBounds: Defaults to true if size is not provided

PolygonHitbox.regular

PolygonHitbox.regular({
  required int sides,
  required double radius,
  Vector2? position,
  double? angle,
  Anchor? anchor,
  bool isSolid = false,
  CollisionType collisionType = CollisionType.active,
})

Implementation Notes

The constructors should generate vertices using:

final vertices = List.generate(sides, (i) {
  final angle = 2 * pi * i / sides;
  return Vector2(radius * cos(angle), radius * sin(angle));
}, growable: false);

More information

This approach for creating convex polygons is currently adopted by a lot of projects. Among them Unreal Engine (in Draw Debug Regular Polygon), SFML (using CircleShape) and bevy engine (using RegularPolygon).

Other

  • Are you interested in working on a PR for this?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions