- Home /
What is a 2D Array?
Ive asked a question on how i should create a grid for a rts, as my was didnt seem to work properly, the first answer was use a 2d array. ive never used a array before so can someone explain on what it is and how can i create one, or aleast a good tutoiral
Thanks
Answer by Next Beat Games · Jan 03, 2013 at 03:51 PM
A 2D Array is simply an array of arrays. Check this tutorial out: http://www.dotnetperls.com/2d-array
Answer by Piflik · Jan 03, 2013 at 03:52 PM
An array is a collection of variables that are easily accessible by a number.
int[] exampleArr = new int[5]; //this is an array of 5 integers (C#)
exampleArr[3] = 5; //stores 5 into the 4th slot of the array...the first slot has number 0
A 2D array is an array of arrays. In each slot of the outer array is a new array.
bool[,] exampleArr2 = new bool[3,5]; //an array of 3x5 boolean values
exampleArr2[1, 3] = false; //stores 'false' into slot (2,4)
THese arrays have to be initialized with their size, since it is not possible to resize them. If you later need a bigger array, you would have to create a new one and copy the values from the smaller one.
how would i use this to create and select parts of the grid for a rts? also it sounds like the grid would not be visable?
The array would only be the internal implementation. You could store simple properties in each slot, like if a tile is occupied or not, or you can create a custom Tile class with several properties, including occupied, what type of ground is there, what unit sits on the tile, etc, and then create an array of this Tile class.
To select a tile, do a raycast and divide the position components by the grid width and you will get the indices of the slot you are pointing at. You can then use these indices to look into the array and see what is stored there.
The grid will not be visible with that alone, this would be a separate issue.
Answer by Eric5h5 · Jan 03, 2013 at 03:54 PM
A 2D array has 2 dimensions, as opposed to a standard array that has 1 dimension.
var myArray : int[]; // standard array
var myArray2 : int[,]; // 2D array
You access it with the x/y coordinates:
var myArray2 = new int[50, 30];
myArray2[45, 25] = 5;
If performance is super-critical you may prefer to use a 1D array (which is faster than a 2D array), and treat it as a 2D array with a bit of math.
var myArray = new int[50 * 30];
myArray[45 + 25*50] = 5;
But in most cases a 2D array would be preferable since it's easier to use.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Having Multiple Controllable FPS Units Selected From A Singular RTS Mode? 0 Answers
Help with Array script 1 Answer
I need help with an array 1 Answer
RTS Grid Idea? 1 Answer