Source

Twisted Potions Double Trouble / Assets / TileMapper / Code / Layer.cs

Full commit
using System;
using UnityEngine;
using System.Collections.Generic;

public class Layer
{
	TileSet tileset;
	string[]  data;
	int currentLayerID;
	int width;
	int height;
	public int vertexCount = 0;
	
	public Layer (TileSet tileset, string data, int currentLayerID, int width, int height)
	{
		this.tileset = tileset;			
		this.data = data.Split (',');
		this.currentLayerID = currentLayerID;
		this.width = width;
		this.height = height;
	}

	public List<Vector3> renderVertices ()
	{
		int dataIndex = 0;
		currentLayerID = currentLayerID * 10;
		List<Vector3> vertices = new List<Vector3> ();
		for (int i = 1; i <= height; i++) {
			for (int j = 1; j <= width; j++) {
				string dataValue = data [dataIndex].ToString ().Trim ();
				if (dataValue != "0") {
					vertices.AddRange (new Vector3[] {
							new Vector3 (tileset.width * (j + 1), tileset.height * (-i + 1), currentLayerID * 1),
							new Vector3 (tileset.width * (j + 1), tileset.height * -i, currentLayerID * 1),							
							new Vector3 (tileset.width * j, tileset.height * (-i + 1), currentLayerID * 1),								
							new Vector3 (tileset.width * j, tileset.height * -i, currentLayerID * 1),
						});	
					vertexCount += 4;
				}
				dataIndex++;
			}
		}
		
		return vertices;
		
	}
	
	public List<Vector2> renderUv ()
	{
		int dataIndex = 0;
		List<Vector2> uv = new List<Vector2> (); 
		int horizontalCellCount = tileset.materialWidth / tileset.width;
		int verticalCellCount = tileset.materialHeight / tileset.height;		
		float cellWidth = ((float)tileset.width / tileset.materialWidth);
		float cellHeight = ((float)tileset.height / tileset.materialHeight);		
		for (int i = 1; i <= height; i++) {
			for (int j = 1; j <= width; j++) {
				string dataValue = data [dataIndex].ToString ().Trim ();
				if (dataValue != "0") {
					int posY = verticalCellCount - (int.Parse (dataValue) / verticalCellCount);
					int posX = int.Parse (dataValue) % horizontalCellCount; 
					uv.AddRange (new Vector2[] {
						new Vector2 (cellWidth * posX, cellHeight * posY),
						new Vector2 (cellWidth * posX, (cellHeight * posY) - cellHeight),
						new Vector2 ((cellWidth * posX) - cellWidth, cellHeight * posY),
						new Vector2 ((cellWidth * posX) - cellWidth, (cellHeight * posY) - cellHeight),

					});	
				}
				dataIndex++;
			}
		}		
		return uv;
	}
	
	public List<int> renderTriangles (int usedVertices)
	{
		int dataIndex = 0;
		List<int> triangles = new List<int> ();
		int currentTri = usedVertices;
		for (int i = 1; i <= height; i++) {
			for (int j = 1; j <= width; j++) {
				string dataValue = data [dataIndex].ToString ().Trim ();
				if (dataValue != "0") {
					triangles.AddRange (new int[] {
							currentTri, currentTri + 1, currentTri + 2,
				            currentTri + 2, currentTri + 1, currentTri + 3,
						});						
					currentTri += 4;
				}
				dataIndex++;
			}
		}
			
		return triangles;
	}		
}