Refactor coordinate system

Signed-off-by: Hans Kokx <hans.d.kokx@gmail.com>
This commit is contained in:
2026-03-14 00:49:31 +01:00
parent 5c9dafbbdf
commit 46712370a4
8 changed files with 83 additions and 29 deletions

View File

@@ -0,0 +1,54 @@
import 'dart:math' as math;
/// A robust, immutable 2D coordinate.
class Coordinate2D implements Comparable<Coordinate2D> {
final double x;
final double y;
const Coordinate2D(this.x, this.y);
/// Factory for a (0,0) coordinate.
static const Coordinate2D zero = Coordinate2D(0.0, 0.0);
// --- Core Logic ---
/// Returns the Euclidean distance between this and [other].
/// Uses the formula: $$d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$$
double distanceTo(Coordinate2D other) {
final dx = x - other.x;
final dy = y - other.y;
return math.sqrt(dx * dx + dy * dy);
}
/// True if both ordinates are finite (not NaN or Infinity).
bool get isValid => x.isFinite && y.isFinite;
Coordinate2D operator +(Coordinate2D other) =>
Coordinate2D(x + other.x, y + other.y);
Coordinate2D operator -(Coordinate2D other) =>
Coordinate2D(x - other.x, y - other.y);
Coordinate2D operator *(double factor) =>
Coordinate2D(x * factor, y * factor);
Coordinate2D operator /(double divisor) =>
Coordinate2D(x / divisor, y / divisor);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Coordinate2D &&
runtimeType == other.runtimeType &&
x == other.x &&
y == other.y;
@override
int get hashCode => Object.hash(x, y);
@override
int compareTo(Coordinate2D other) {
if (x != other.x) return x.compareTo(other.x);
return y.compareTo(other.y);
}
@override
String toString() => 'Coordinate($x, $y)';
}