apply method

  1. @override
void apply(
  1. ForceSimulation simulation
)
override

Applies the force to the simulation.

Implementation

@override
void apply(ForceSimulation simulation) {
  final alpha = simulation.alpha;

  for (int iter = 0; iter < iterations; iter++) {
    for (final link in links) {
      final source = simulation.getNode(link.source);
      final target = simulation.getNode(link.target);

      if (source == null || target == null) continue;

      var dx = target.x - source.x;
      var dy = target.y - source.y;
      var dist = math.sqrt(dx * dx + dy * dy);

      if (dist == 0) {
        dist = 0.001;
        dx = dist;
      }

      final targetDist = distance * link.weight;
      final force = (dist - targetDist) / dist * alpha * strength;

      dx *= force;
      dy *= force;

      const sourceWeight = 1.0;
      const targetWeight = 1.0;
      const totalWeight = sourceWeight + targetWeight;

      if (!target.fixed) {
        target.vx -= dx * sourceWeight / totalWeight;
        target.vy -= dy * sourceWeight / totalWeight;
      }

      if (!source.fixed) {
        source.vx += dx * targetWeight / totalWeight;
        source.vy += dy * targetWeight / totalWeight;
      }
    }
  }
}