randomPointAlongEdges static method

Vector2 randomPointAlongEdges(
  1. List<Vector2> vertices, {
  2. Random? random,
})

Returns a random point on the vertices.

Implementation

static Vector2 randomPointAlongEdges(
  List<Vector2> vertices, {
  Random? random,
}) {
  final randomGenerator = random ?? randomFallback;
  final verticesLengths = <double>[];
  var totalLength = 0.0;
  for (final (i, startPoint) in vertices.indexed) {
    final endPoint = vertices[(i + 1) % vertices.length];
    final length = startPoint.distanceTo(endPoint);
    verticesLengths.add(length);
    totalLength += length;
  }
  final pointOnEdges = randomGenerator.nextDouble() * totalLength;
  var vertexIndex = 0;
  var currentEndPoint = 0.0;
  late final double localEdgePoint;
  while (vertexIndex < verticesLengths.length) {
    final lastEndPoint = currentEndPoint;
    currentEndPoint += verticesLengths[vertexIndex];
    if (currentEndPoint >= pointOnEdges) {
      localEdgePoint = pointOnEdges - lastEndPoint;
      break;
    }
    vertexIndex++;
  }
  final startPoint = vertices[vertexIndex];
  final endPoint = vertices[(vertexIndex + 1) % vertices.length];
  tmpVector2
    ..setFrom(endPoint)
    ..sub(startPoint)
    ..scaleTo(localEdgePoint);
  return startPoint + tmpVector2;
}