[Suggest] Add `Vector3Int.ManhattanDistance(Vector3Int a, Vector3Int b)`.

I want methods to calculate Manhattan distance with Vector3Ints.

There is a method to calculete Euclidean distance (Vector3.Distance(Vector3 a, Vector3 b), but sometime we need the method to calculate Manhattan distance in tile based game logic.

I think many of us creted the method to calculate Manhattan distance.

I suggest to create static methods in Vector3Int

// in Vector3Int
public static int ManhattanDistance(Vector3Int a, Vector3Int b){
    checked {
        return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y) + Mathf.Abs(a.z - b.z);
    }
}

and with Vector2Int

// in Vector2Int
public static int ManhattanDistance(Vector2Int a, Vector2Int b){
    checked {
        return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
    }
}

update : added checked

6 Likes

Thanks men is wonderfull code.

Greetings from Colombia

You can add your own static extensions of Vector3Int to do this as well for better ease of use, though they definitely should implement it internally.

// in Vector2Int
public static int ManhattanDistance(this Vector2Int a, Vector2Int b){
    checked {
        return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
    }
}

And then your code simply becomes position1.ManhattanDistance(position2);

3 Likes