globalToLocal method

Vector2 globalToLocal(
  1. Vector2 point, {
  2. Vector2? output,
})

Transform point from the global coordinate space into the local coordinates. Thus, this method performs the inverse of the current transform.

If the current transform is degenerate due to one of the scale factors being 0, then this method will return a zero vector.

Use output to send in a Vector2 object that will be used to avoid creating a new Vector2 object in this method.

Implementation

Vector2 globalToLocal(Vector2 point, {Vector2? output}) {
  // Here we rely on the fact that in the transform matrix only elements
  // `m[0]`, `m[1]`, `m[4]`, `m[5]`, `m[12]`, and `m[13]` are modified.
  // This greatly simplifies computation of the inverse matrix.
  final m = transformMatrix.storage;
  var det = m[0] * m[5] - m[1] * m[4];
  if (det != 0) {
    det = 1 / det;
  }
  final x = ((point.x - m[12]) * m[5] - (point.y - m[13]) * m[4]) * det;
  final y = ((point.y - m[13]) * m[0] - (point.x - m[12]) * m[1]) * det;
  return (output?..setValues(x, y)) ?? Vector2(x, y);
}