thesadrogue / TheSadRogue.Primitives

A collection of primitive data structures for working with a 2-dimensional grid.
MIT License
21 stars 6 forks source link

Add Operators to Point and Direction #88

Open Chris3606 opened 2 years ago

Chris3606 commented 2 years ago

Currently, you can do somePoint + someDirection to translate a point in a direction, however there are a few similar operations that either feel like they should work but don't, or would be handy in similar ways to this one:

var p = new Point(1, 2);

// Translate UpLeft using the translate function.
// Feels like it should work since the function accepts a delta,
// but overload does not exist.
p = p.Translate(Direction.UpLeft);

// Either one of these could translate the coordinate up left 3 times;
// Doesn't work because the * operator for Directions doesn't exist.
p.Translate(Direction.UpLeft * 3);
p = p + Direction.UpLeft * 3;

I propose the definition of the following functions to remedy this:

// In Point class
public Point Translate(Direction dir) => return new Point(X + dir.DeltaX, Y + dir.DeltaY);

// In direction class
public static Point operator*(Direction dir, int value) => new Point(dir.DeltaX * value, dir.DeltaY * value);
public static implicit operator Point(Direction dir) => new Point(dir.DeltaX, dir.DeltaY);
Chris3606 commented 10 months ago

Also operator-(Point p) => new(-p.x, -p.y);