Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice
  2. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  3. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[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:
    24
    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,539
    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, m_craig36 and Q-Ted like this.