Modulus (%) to traverse 2D tile sheet horizontally, vertically
Notes:
I. Properties of modulus and division operators: [Starts at: 00min:40sec]
II. Processing 2D tile sheet horizontally (row by row): [Starts at:09min:20sec ]
III. Processing 2D tile sheet vertically ( col by col): [Starts at: 14min:36sec]
IV. Testing a number is even or odd using modulus operator : [Starts at: 26min:48sec]
V. Testing a number is divisible by another number using mod : [Starts at: 28min:16sec]
I. Properties of modulus and division operators: [Starts at: 00min:40sec]
Modulus (%) and division (/) operators are used to process column wise or row wise.
1. 2d array
2. 2d tile map
3. 2d sprite sheet
4. Level designing etc.
Modulus(%) is used to lock the result, or get repeated sequence
Ex:
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
4 % 2 = 0
5 % 2 = 1
6 % 2 = 0
7 % 2 = 1
8 % 2 = 0
9 % 2 = 1
Division(/) is used to get same number repeatedly : (int/int=int)
Ex:
0 / 2 = 0
1 / 2 = 0
2 / 2 = 1
3 / 2 = 1
4 / 2 = 2
5 / 2 = 2
6 / 2 = 3
7 / 2 = 3
8 / 2 = 4
9 / 2 = 4
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
/*
for (int i = 0; i < 10; i++) {
Debug.Log (string.Format ("{0} {1}", i / 2, i % 2));
}
*/
for (int i = 0; i < 10; i++) {
Debug.Log (string.Format ("{0} {1}", i / 3, i % 3));
}
}
}
II. Processing 2D tile sheet horizontally (row by row): [Starts at:09min:20sec ]
Formula:
r = tile / numOfCols;
c = tile % numOfCols;
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
// Horizontally looping 2D Tile map (row by row)
int numRows = 3;
int numCols = 3;
int tile = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
int r = tile / numCols;
int c = tile % numCols;
Debug.Log(string.Format("r = {0} and c={1}",r,c));
tile++;
}
}
}
}
III. Processing 2D tile sheet vertically ( col by col): [Starts at: 14min:36sec]
Formula:
r = tile % numOfRows;
c= tile / numOfRows;
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour {
void Start () {
// Vertically looping 2D Tile map ( col by col)
int numRows = 3;
int numCols = 3;
int tile = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
int r = tile % numRows;
int c = tile / numRows;
Debug.Log(string.Format("r = {0} and c={1}",r,c));
tile++;
}
}
}
}
IV. Testing a number is even or odd using modulus operator : [Starts at: 26min:48sec]
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
int num = 11;
if (num % 2 == 0)
Debug.Log (num + " is even");
else
Debug.Log (num + " is odd");
}
}
V. Testing a number is divisible by another number using mod : [Starts at: 28min:16sec]
Example code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
int num = 11;
if (num % 2 == 0)
Debug.Log (num + " is divisible by 2");
else
Debug.Log (num + " is not divisible by 2");
}
}