Search Unity

Using a bitmask for hexagon connections?

Discussion in 'Scripting' started by c-Row, Feb 20, 2021.

  1. c-Row

    c-Row

    Joined:
    Nov 10, 2009
    Posts:
    853
    On a map made up of hexagons I would like to put sprites on cells when there is a road, indicating this cell is connected to one or more of its neighbor cells. For the individual sprites I would like to set up prefabs for each possible variant.

    Now, rather than set up six different (60° rotated) variants for each possible connection variation I would like to use something like a bitmask do reduce some of the workload.

    hexShift.png
    For example, a connection from North East to South East would have the first and third bit set (000101).

    Here comes the tricky part - when looking up prefabs, I would like to loop through all these and find the prefab that matches the variant but not necessarily the rotation, so instead of having to set up a prefab with a bitmask of 101000 I want to find the tile that matches the bitmask shifted to whichever position (000101,001010, 010100 and so on) and rotate its SpriteRenderer accordingly.

    As far as I understand bitmask are always 32 bits in length so I suppose this is not possible out-of-the-box? And if it was, how can I shift a whole bitmask, and will it "wrap"?

    Is there another way to solve this in a similar manner?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    Just on the subject of hexagons, I always like to post this guy's work:

    Hexagonal maps (hexmaps):

    https://www.redblobgames.com/grids/hexagons/

    You can certainly use bitmasks for what you're accomplishing above, but in today's ultra-fast CPU world, unless you are literally making millions of map cells all at once, you probably could get plenty of performance by using some type of binary-digits-in-a-string descriptor, like "000101"

    I would actually prerotate the six possibilities and inject them into a Dictionary that contained a link to the prefab that has those rotations and what rotation (0 to 5) it would be to make it match.

    Such as:

    "000101" would be prefab X rotation 0

    "001010" would be prefab X rotation 1

    "101000" would be prefab X rotation 3

    etc.

    Jam those into a Dictionary and look 'em up by string, super-fast and far easier to debug than printing bits out. :)
     
    SparrowGS and c-Row like this.
  4. c-Row

    c-Row

    Joined:
    Nov 10, 2009
    Posts:
    853
    Ohhhh, now that is a pretty neat idea! Thanks for the suggestion.
     
    Kurt-Dekker likes this.