Skip to content

Instantly share code, notes, and snippets.

@poemdexter
Last active December 23, 2019 16:27
Show Gist options
  • Save poemdexter/11046062 to your computer and use it in GitHub Desktop.
Save poemdexter/11046062 to your computer and use it in GitHub Desktop.
Representing a 2D array as a 1D array with wrapping sides (up at top of 1st column will place you bottom of 1st column)
using UnityEngine;
using System.Collections;
public class TileManager : MonoBehaviour
{
public GameObject walkableTile;
public GameObject blockingTile;
private GameObject[] tiles = new GameObject[25];
public int offset = 0; // current position on grid array
public enum Direction
{
Up = 1,
Down = -1,
Left = 5,
Right = -5
}
void Start()
{
InstantiateArrayTiles();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
GetTile(Direction.Left);
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
GetTile(Direction.Right);
}
else if (Input.GetKeyDown(KeyCode.UpArrow))
{
GetTile(Direction.Up);
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
GetTile(Direction.Down);
}
}
private void InstantiateArrayTiles()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
GameObject tile = Instantiate(walkableTile, new Vector2(1.1f * i, 1.1f * j), Quaternion.identity) as GameObject;
tile.transform.parent = transform;
tile.name = ((i * 5) + j).ToString();
tiles[(i * 5) + j] = tile;
}
}
transform.position = new Vector2(-2.2f, -2.2f);
}
private GameObject GetTile(Direction dir)
{
if (dir == Direction.Left || dir == Direction.Right)
{
offset += (int)dir;
int x = Mod(offset, 25);
return tiles[x];
}
else
{
// 4 9 14 19 24
// 3 8 13 18 23
// 2 7 12 17 22
// 1 6 11 16 21
// 0 5 10 15 20
// get current column position (0 - 4)
int a = Mod(offset, 25);
int currentCol = (int)Mathf.Floor(a / 5);
offset += (int)dir; // move current position in direction
int newRow = Mod(offset, 5); // get vertical position in column (0 - 4)
// set our current position to proper 'next' tile
offset = (currentCol * 5) + newRow;
return tiles[offset];
}
}
// C# doesn't have modulus so lets write our own
private int Mod(int a, int b)
{
int x = a % b;
if (x < 0) x += b;
return x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment