unity2017官方已经支持了瓷砖,但我自己也写了个简单的自动瓷砖,权当学习,效果如图。
image
主要实现了两个功能:
① 根据周围格子的状态改变自己的状态
② 对2D物理碰撞体进行自动合并,优化性能
基本思路是遍历特定范围中的每个GameObjec,然后计算坐标,再通过坐标来处理瓷砖间的相对关系。先看基类,主要处理变换坐标的工作:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoTile : MonoBehaviour
{
/* 图块边长 */
public float sideLength;
/* 是否合并碰撞体 */
public bool isCoillder;
/* 左下角的起始块,标定开始计算的位置 */
public GameObject startOne;
/* 存储地图 */
List mapContainer = new List();
protected Transform[] childrenTransforms;
/* 存储子物体 */
protected Vector2 basePoint;
/* 从startone获取的起点 */
/* 初始化起点 */
protected void intinalBasePoint()
{
basePoint = startOne.transform.position;
/* Debug.Log ("BasePoint=" + basePoint); */
}
/* 初始化存储块信息的变长数组 */
protected void intinalMapContainer()
{
/* 获取子物体的数组 */
childrenTransforms = GetComponentsInChildren ( false );
foreach ( Transform tra in childrenTransforms )
{
/* 利用tag判断是否纳入计算 */
if ( tra.tag == "Tile" )
{
Vector2 pos = tra.position;
int x, y;
x = (int) ( (pos.x - basePoint.x) / sideLength + 0.05f);
/* 加0.05防止误差 */
y = (int) ( (pos.y - basePoint.y) / sideLength + 0.05f);
/* 判断是否延长主组 */
while ( mapContainer.Count <= x )
{
mapContainer.Add( new ArrayList() );
}
/* 向列数组填充元素 */
while ( mapContainer [x].Count <= y )
{
mapContain