Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Calculating x & y position of tiles in 2D level, Creating 3D array

Notes:

I. Calculating x and y position of tiles in a 2D level : [Starts at:00min:00sec]
II. Creating 3D array and its memory representation: [Starts at:14min:38sec]

I. Calculating x and y position of tiles in a 2D level : [Starts at:00min:00sec]

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {

int[,] level2 = new int[,]{
{1,1,1,1,2},
{1,1,1,2,0},
{1,1,2,0,0},
{1,2,0,0,0},
{2,0,0,0,0}
};

int WIDTH = 100;
int HEIGHT = 100;
int tileNum = 0;
int xPos = 0;
int yPos = 0;
int numCols = 5;

for (int row = 0; row < level2.GetLength(0); row++) {
for (int col = 0; col < level2.GetLength(1); col++) {

xPos = tileNum % numCols * WIDTH;
yPos = tileNum / numCols * HEIGHT;

switch (level2 [row, col]) {
case 1:
Debug.Log (string.Format ("Draw brick at {0} and {1}", xPos, yPos));
break;
case 2:
Debug.Log (string.Format ("Draw red brick at {0} and {1}", xPos, yPos));
break;
}

tileNum++;

}
}

}
}

II. Creating 3D array and its memory representation: [Starts at:14min:38sec]

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {

// Creating and initializing 3D array
int[,,] numbers = new int[2,2,2]{
{
{0,1},
{1,0}
},
{
{0,1},
{1,0}
}
};

// traversing 3D array
for (int x = 0; x < numbers.GetLength(0); x++) {
for (int y = 0; y < numbers.GetLength(1); y++) {
for (int z = 0; z < numbers.GetLength(2); z++) {
Debug.Log (numbers [x, y, z]);
}
}
}
}
}