问题
In the game I am making, I have a level that is created through an XML file. The level is drawn with a nested for loop. I am trying to make another nested for loop to take the position of each tile and assign it to a jagged array. I want to do this so I can make collision detection for each tile.
Each tile in the picture of the example level below is 20x20 pixels, with 30x30 tiles, for a screen resolution of 600x600. The level was made with the free software Realm Factory, which lacks documentation, along with no real support... But, currentLevel.Rows will equal 30 here, and same for currentLevel.Columns.
Below is what I have attempted to create so far, bit it's not much. My brain just refuses to understand jagged arrays, no matter how much I try. I can't even figure out how to create them!
int a = 0;
int b = 0;
int x = 0;
int y = 0;
int[,] size = new int[currentLevel.Rows, currentLevel.Columns]'
int[,] pos = new int[600,600];
int[] tiles = new int[600];
for (a = 0; a < 600; a += 20, x++)
{
for (b = 0; b < 600; b += 20, y++)
{
size[x][y] = ;
}
}
What I want to assign to tiles[x,y] is the X and Y position of each tile, so then I can add collision to each tile.
Thank you so much to anyone who can help me. I love programming, but I'm not so good at math and visual-spatial skills...
回答1:
Position is a point (it has an abscissa and an ordinate), not an integer. Besides, if you have a matrix (20x20 in tiles, or 600x600 in pixels) , why are you trying to store it in jagged array? This is what multidimensional arrays are intended for:
var tileSize = 20;
var screenSizeInTiles = 30;
// initializing multidimensional array of points
var tilePositions = new Point[screenSizeInTiles, screenSizeInTiles];
for (var x = 0; x < screenSizeInTiles; x++)
{
for (var y = 0; y < screenSizeInTiles; y++)
{
tilePositions[x, y] = new Point(x * tileSize, y * tileSize);
}
}
Compare with jagged array:
// initializing jagged array of points
var tilePositions = new Point[screenSizeInTiles][];
for (var i = 0; i < screenSizeInTiles; i++)
{
// each item in a jagged array is a one-dimensional array of points.
tilePositions[i] = new Point[screenSizeInTiles];
}
for (var x = 0; x < screenSizeInTiles; x++)
{
for (var y = 0; y < screenSizeInTiles; y++)
{
tilePositions[x][y] = new Point(x * tileSize, y * tileSize);
}
}
As you can see, multidimensional array is a entity, which guarantees, that every row has the same size, as the other rows, the same is true for columns.
Jagged arrays, in turn, are arrays of arrays, where each member (array) can have length, which differs from the lengths of its "neighbors".
Of course, you can represent matrix as jagged array, this will be particular case (all members of jagged array will have the same length), but this is less convenient to use.
P.S. I've used Point
structure from here.
来源:https://stackoverflow.com/questions/13853166/how-can-i-use-a-jagged-array-to-record-the-x-and-y-axes-of-these-tiles