Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

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

Discussion in '2D Experimental Preview' started by RyotaMurohoshi, Dec 6, 2016.

  1. RyotaMurohoshi

    RyotaMurohoshi

    Joined:
    Jun 20, 2013
    Posts:
    27
    I want methods to calculate Manhattan distance with `Vector3Int`s.

    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.

    https://docs.unity3d.com/ja/current/ScriptReference/Vector3.Distance.html

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

    I suggest to create static methods in Vector3Int

    Code (CSharp):
    1. // in Vector3Int
    2. public static int ManhattanDistance(Vector3Int a, Vector3Int b){
    3.     checked {
    4.         return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y) + Mathf.Abs(a.z - b.z);
    5.     }
    6. }
    and with Vector2Int

    Code (CSharp):
    1. // in Vector2Int
    2. public static int ManhattanDistance(Vector2Int a, Vector2Int b){
    3.     checked {
    4.         return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
    5.     }
    6. }
    update : added checked
     
    Last edited: Dec 6, 2016
  2. Sdk_fn

    Sdk_fn

    Joined:
    Sep 29, 2015
    Posts:
    4
    Thanks men is wonderfull code.

    Greetings from Colombia
     
  3. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,560
    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.


    Code (CSharp):
    1. // in Vector2Int
    2. public static int ManhattanDistance(this Vector2Int a, Vector2Int b){
    3.     checked {
    4.         return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
    5.     }
    6. }
    And then your code simply becomes
    position1.ManhattanDistance(position2);
     
    joshtemple, berber_hunter and Q-Ted like this.