Search code examples
c#arraysmath

How to map 8 directions to 1D array


I have 8 cursors for 8 directions on screen.

directions on screen

I want to put them into array and chose them depending on direction vector. The order does not matter, but I need to assign i coordinate in 1D array for every vector seen above. I spend a long time trying to invent the formula for it, but nothing would work.

The values in vector can be 0,1,-1.

Pseudo code:

Cursor getCursor(int x, int y) {
    int i = TheFunctionINeed(x,y);
    return cursors[i];
}

Note: Because so many guys were confused by what do I want, I used the answer to make following fiddle: Mapping vectors to array.


Solution

  • it contains 9 elements, I have added (0, 0) for simplicity.

    a = {(-1, -1),  (-1, 0),  (-1, 1),  (0, -1),  (0, 0),  (0, 1),  (1, -1),  (1, 0),  (1, 1)}
    
    
    ZeroBasedIndex(x, y) = (x + 1) * 3 + (y + 1)