Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Calculating X and Y position of each tile in a tile map

Notes:

I. Calculating X and Y position of each tile in a tile map : [Starts at:00min:00sec]

Example Code:

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

// 2 by 2 tile map
int[] xPos = new int[4];
int[] yPos = new int[4];

int tileNum = 0;

int tileWidth = 100;
int tileHeight = 100;

// vertical placement ( x be same y be incrementing)
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
xPos [tileNum] = x * tileWidth;
yPos [tileNum] = y * tileHeight;
Debug.Log (string.Format ("X={0} and y={1}", xPos [tileNum], yPos [tileNum]));
tileNum++;
}
}

tileNum = 0;

// horizontal placement ( y be same x be incrementing)
for (int y = 0; y < 2; y++) {
for (int x = 0; x < 2; x++) {
xPos [tileNum] = x * tileWidth;
yPos [tileNum] = y * tileHeight;
Debug.Log (string.Format ("X={0} and y={1}", xPos [tileNum], yPos [tileNum]));
tileNum++;
}
}
}
}

Note: When using x and y for calculating xpos and ypos, we switch loops for horizontal and vertical placement

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

// 2 by 2 tile map
int[] xPos = new int[4];
int[] yPos = new int[4];

int tileNum = 0;

int tileWidth = 100;
int tileHeight = 100;

int totalRows = 2;
int totalCols = 2;

// vertical placement (row wise)
for (int x = 0; x < totalCols; x++) {
for (int y = 0; y < totalRows; y++) {
xPos [tileNum] = tileNum / totalRows * tileWidth;
yPos [tileNum] = tileNum % totalRows * tileHeight;
Debug.Log (string.Format ("X={0} and y={1}", xPos [tileNum], yPos [tileNum]));
// (0,0), (0,100), (100,0), (100, 100)
tileNum++;
}
}

tileNum = 0;

// horizontal placement (column wise)
for (int x = 0; x < totalCols; x++) {
for (int y = 0; y < totalRows; y++) {
xPos [tileNum] = tileNum % totalCols * tileWidth;
yPos [tileNum] = tileNum / totalCols * tileHeight;
Debug.Log (string.Format ("X={0} and y={1}", xPos [tileNum], yPos [tileNum]));
// (0,0), (100,0), (0, 100), (100,100)
tileNum++;
}
}
}
}

Note: When using tile number for calculating xpos and ypos, we need not to switch loops for horizontal and vertical placement

Note:
When using % and / you can nest loop any way
Whereas
When using *
1. For vertical placement x should be outside
2. For horizontal placement y should be outside