computeDistanceToOut method

  1. @override
double computeDistanceToOut(
  1. Transform xf,
  2. Vector2 p,
  3. int childIndex,
  4. Vector2 normalOut,
)
override

Compute the distance from the current shape to the specified point. This only works for convex shapes.

xf is the shape world transform. p is a point in world coordinates. normalOut returns the direction in which the distance increases. Returns the distance from the current shape.

Implementation

@override
double computeDistanceToOut(
  Transform xf,
  Vector2 p,
  int childIndex,
  Vector2 normalOut,
) {
  final xfqc = xf.q.cos;
  final xfqs = xf.q.sin;
  final xfpx = xf.p.x;
  final xfpy = xf.p.y;
  final v1x = (xfqc * vertex1.x - xfqs * vertex1.y) + xfpx;
  final v1y = (xfqs * vertex1.x + xfqc * vertex1.y) + xfpy;
  final v2x = (xfqc * vertex2.x - xfqs * vertex2.y) + xfpx;
  final v2y = (xfqs * vertex2.x + xfqc * vertex2.y) + xfpy;

  var dx = p.x - v1x;
  var dy = p.y - v1y;
  final sx = v2x - v1x;
  final sy = v2y - v1y;
  final ds = dx * sx + dy * sy;
  if (ds > 0) {
    final s2 = sx * sx + sy * sy;
    if (ds > s2) {
      dx = p.x - v2x;
      dy = p.y - v2y;
    } else {
      dx -= ds / s2 * sx;
      dy -= ds / s2 * sy;
    }
  }

  final d1 = sqrt(dx * dx + dy * dy);
  if (d1 > 0) {
    normalOut.x = 1 / d1 * dx;
    normalOut.y = 1 / d1 * dy;
  } else {
    normalOut.x = 0.0;
    normalOut.y = 0.0;
  }
  return d1;
}