# Translating a world position to an array position

Lets keep this simple, so, assuming I have an array like this ...

var array = new bool[10,10,10];


.. and then I have a start and end vector3 ...

var start = new Vector3(-21,-21,-21);
var end = new Vector3(-10,-10,-10);


... these booleans represent some data for a part of my virtual world, but they are a small chunk of that data between the start and end points in the world.

How do I, given a point in the virtual world translate that position to a point in the array ...

var pos = new Vector3(-20,-20,-20);

var result = GetValueAt(pos);

bool GetValueAt(Vector3 pos)
{
// my question is:
//what goes in here to translate from pos to array pos [1,1,1] ?
return array[1,1,1];
}


Simply subtract the start-vector from the position-vector and you get the array indices.

bool GetValueAt(Vector3 pos)
{
return array[pos.x - start.x, pos.y - start.y, pos.z - start.z ];
}


You might also want to add some error-checking in case the caller provides a position outside of the array.

Also, this code assumes that all three coordinates of start are smaller than those of end. When that is not always the case, you need to find the smaller value on each axis and subtract that one from the corresponding axis of pos.

var pos = new Vector3(-20,-20,-20);

var result = GetValueAt(pos);

bool GetValueAt(Vector3 pos)
{
return array[pos.x, pos.y, pos.z];
}


You can just pull the coords out separately.

• This won't work. You can't access an array with indices of -20, -20 and -20. Those are not valid indices, it's outside the bounds of the array.
– House
Apr 3 '16 at 0:50