Reputation: 53139
I have 8 cursors for 8 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.
Upvotes: 3
Views: 2930
Reputation: 2539
I have a easiest way to map this. Simply define your array like this
ax8 = [-1,-1,0,1,1,0,-1,1,-1]
Now loop through till 8, it will give all the points
for i in range(8):
print(ax8[i], ax8[i+1])
It will rotate clockwise and pick the coordinates one by one. Hope this helps!
Upvotes: 1
Reputation: 21999
To map (x,y) as 1d array people uses common formula
index = x + y * (xmax + 1)
Let's try to do same for (x,y,z), taking in account what all values are in range [-1;1] (can have one of tree values: -1
, 0
or 1
).
First only for (x,y), note, you need offset to avoid negative indexes
xy = (x + 1) + (y + 1) * 3
Now mapping (xy; z), note that xymax
value is 8
xyz = xy + (z + 1) * 9
Which makes final formula
index = (x + 1) + (y + 1) * 3 + (z + 1) * 9.
Testing:
vector index
------------------
(-1,-1,-1) 0
(0,0,0) 13
(1,1,1) 27
Upvotes: 3
Reputation: 401
I would also add 0,0 to make the calculation easier.
The function you need, let's call it "GetCursorIndex", can work like this:
int getCursorIndex(int x, int y)
{
return (x+1)+(y+1)*3;
}
If you have your Cursors sorted, so that the first represents -1, -1 and the last one 1, 1 you can add a the one for -1, 0 or 1, 0 in in the central Position of the Array, twice... or you can create a Cursor for the Position 0,0... maybe it makes sense.
Upvotes: 2
Reputation: 32266
Another option would be to use Dictionary<Tuple<int,int>,Cursor>
.
var cursors = new Dictionary<Tuple<int,int>, Cursor>();
cursors.Add(new Tuple<int,int>(-1,-1), someCursorHere);
// continue filling it in for each vector.
Cursor getCursor(int x, int y)
{
Cursor c;
if(cursors.TryGetValue(new Tuple<int,int>(x,y), out c)
return c;
// throw an exception here or return a default value?
}
Upvotes: 1
Reputation: 26
You could arbitrarily start at a spot such as the upper left corner and order them going around clockwise.
So: [-1,-1] = 0, [-1,0] = 1, etc.
Upvotes: -1
Reputation: 20754
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)
Upvotes: 5