clamp method

Vec2 clamp(
  1. Vec2 point
)

Clamps the given point to the nearest point that is within the bounds of this Rect. Returns the clamped point as a new Vec2.

For this operation, the rectangle is treated as a group of columns and ows. For example, consider the Rect defined by top=1, right=4, bottom=5, left=1. This rectangle consists of 3 columns (right - left) and 4 rows (bottom - top). This means that the rectangle would clamp the Vec2 (4, 5) to (3, 4).

The exception to this is when the rectangle has a width or height of zero, in which case it's impossible to clamp any vector within the bounds of the rectangle. In this case, a StateError will be thrown.

Implementation

Vec2 clamp(Vec2 point) {
  if (size.x == 0 || size.y == 0) {
    throw StateError(
        'Cannot clamp a vector inside a Rect with width or height of 0');
  }

  var x = point.x.clamp(left, right - 1).toInt();
  var y = point.y.clamp(top, bottom - 1).toInt();
  return Vec2(x, y);
}