您的位置:首页 > 职场人生

Data structures for game programming learning notes (四)——multi-dimensional array

2007-10-29 13:02 381 查看
The general formula for converting a 2D coordinate into a 1D coordinate is:
Y * width + x
If you want to convert 3D array into 1D array, then
(z * width * height) + (y * width) + (x)

Passing multi-dimensional arrays to functions
1) The most popular way is to have the function assume that it will be receiving an array of a specific size, like this:
void Function( int p_array2d[4][5], int p_array3d[2][4][2] );
2) To pass a 2D array into a function, you are required to at least give the width of the array as a parameter, like this:
void Function( int p_array[][4] );
Note: The order can not be reversed. Also, it is usually a good idea to pass in another variable to the function telling it how large the variable dimension is. For example:
void Process( int p_monsters[][3], int p_monstertypes );

The Array2D class
template <class Datatype>
class Array2D
{
private:
Datatype* m_array;
int m_width;
int m_height;
public:
// The constructor
Array2d(int p_width, int p_height)
{
m_array = new Datatype[p_width * p_height];
m_width = p_width;
m_height = p_height;
}
// The destructor
~Array2D()
{
if(m_array != 0)
delete[] m_array;
m_array = 0;
}
// The get function
Datatype& Get(int p_x, int p_y)
{
Return m_array[p_y * m_width + p_x];
}
// The resize function
void Resize(int p_width, int p_height)
{
Datatype* newarray = new Datatype[p_width * p_height];
if (newarray == 0)
return;
int x, y, t1, t2;
int minx = (p_width < m_width ? p_width : m_width);
int miny = (p_height < m_heigtht ? p_height : m_height);
for (y = 0; y < miny; ++y)
{
t1 = y * p_width;
t2 = y * m_width;
for (x = 0; x < minx; ++x)
{
newarray[t1 + x] = m_array[t2 + x];
}
}
If (m_array != 0)
Delete[] m_array;
m_array = newarray;
m_width = p_width;
m_height = p_height;
}
// Get the size of the array
int Width()
{
return m_width;
}
int Height()
{
return m_height;
}
int Size()
{
return m_width * m_height;
}
};

Tilemaps
A tilemap is a 2D array of tiles, in which each tile acts like a pixel on its own. Tilemaps are used quite often in games, and they still have applications in newer 3D games.
Because tilemaps allow you to abstract the idea of pixels to a higher level, this significantly simplifies a drawing engine.

The layerd tilmaps allow you to have two or more layers on your tilemap.

Analysis of multi-dimensional arrays in games
Multi-dimensional arrays are more suited to specific problems. Although memory concerns are no longer a primary concern with game programming, don’t forget that multi-dimensional arrays do not increase in size linearly.
Perhaps the largest thing you should be concerned with when dealing with multi-dimensional arrays is how to iterate through them.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息