Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Placing images or tiles in rows and columns on X Y plane

Notes:

I. Placing images / tiles horizontally: [Starts at:02min:08sec]
II. Adding space between images or tiles: [Starts at:06min:48sec]
III. Placing images/tiles in rows and columns: [Starts at:18min:16sec]

I. Placing images or tiles horizontally: [Starts at:02min:08sec]

Lets take there are 5 images/titles and each image/tile width is 100
xPos of images should be 0, 100, 200, 300, 400

// Math
// 0 * 100 = 0
// 1 * 100 = 100
// 2 * 100 = 200
// 3 * 100 = 300
// 4 * 100 = 400

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour
{
void Start ()
{
int[] xPos = new int[5];
const int WIDTH = 100;

for (int i = 0; i < xPos.Length; i++)
{
xPos [i] = i * WIDTH;
Debug.Log (xPos [i]); // 0, 100, 200, 300, 400
}
}
}

II. Adding space between images or tiles: [Starts at:06min:48sec]

Lets take there are 5 images/titles and each image/tile width is 100
After adding 10 px space between images
xPos of images should be: 0, 110, 220, 330, 440

//Math for shifting all images by 10 px is:
0 * 100 + 10 = 10
1 * 100 + 10 = 110
2 * 100 + 10 = 210
3 * 100 + 10 = 310
4 * 100 + 10 = 410

//Correct math for adding 10 px space between images is:
0 * ( 100 + 10 ) = 0 * 110 = 0
1 * ( 100 + 10 ) = 1 * 110 = 110
2 * ( 100 + 10 ) = 2 * 110 = 220
3 * ( 100 + 10 ) = 3 * 110 = 330
4 * ( 100 + 10 ) = 4 * 110 = 440

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour
{
void Start ()
{
int[] xPos = new int[5];
const int WIDTH = 100;

for (int i = 0; i < xPos.Length; i++)
{
//xPos [i] = i * WIDTH + 10; // shifts all images by 10 px
//Debug.Log (xPos [i]); // 10, 110, 210, 310, 410

// Correct way for adding 10 px space between images is
xPos[i] = i * ( WIDTH + 10 );
Debug.Log(xPos[i]); // 0, 110, 220, 330, 440
}
}
}

III. Placing images/tiles in rows and columns: [Starts at:18min:16sec]

2 by 2 tile map
tile0 = (0,0)
tile1 = (100,0)
tile2 = (0,100)
tile4 = (100,100)

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour
{
void Start ()
{
int[] xPos = new int[2];
int[] yPos = new int[2];
const int WIDTH = 100;
const int HEIGHT = 100;

// y indicates rows and x indicates columns
for (int y = 0; y < yPos.Length; y++)
{
for (int x = 0; x < xPos.Length; x++)
{
xPos [x] = x * WIDTH;
yPos [y] = y * HEIGHT;
Debug.Log (string.Format ("({0},{1})", xPos [x], yPos [y]));
}
}

// OR
int tile=0;
for (int y = 0; y < yPos.Length; y++)
{
for (int x = 0; x < xPos.Length; x++)
{
xPos [x] = (tile % 2) * WIDTH;
yPos [y] = (tile / 2) * HEIGHT;
Debug.Log (string.Format ("({0},{1})", xPos [x], yPos [y]));
tile++;
}
}
}
}