Unity 编辑器扩展 Chapter2—Gizmos-LMLPHP

二. 使用Gizoms绘制网格及矩阵转换使用

1. 创建Leve类,作为场景控制类:

 using UnityEngine;
//使用namespace方便脚本管理
namespace RunAndJump {
//使用部分类partial将类依据不同的功能分布到各个文件中,便于功能区分个管理
public partial class Level : MonoBehaviour {
[SerializeField]
public int _totalTime = ;
[SerializeField]
private float _gravity = -;
[SerializeField]
private AudioClip _bgm;
[SerializeField]
private Sprite _background; [SerializeField]
private int _totalColumns = ; [SerializeField]
private int _totalRows = ; public const float GridSize = 1.28f; private readonly Color _normalColor = Color.grey;
private readonly Color _selectedColor = Color.yellow;
public int TotalTime {
get { return _totalTime; }
set { _totalTime = value; }
} public float Gravity {
get { return _gravity; }
set { _gravity = value; }
} public AudioClip Bgm {
get { return _bgm;}
set { _bgm = value; }
} public Sprite Background {
get { return _background; }
set { _background = value; }
} public int TotalColumns
{
get
{
return _totalColumns;
} set
{
_totalColumns = value;
}
} public int TotalRows
{
get
{
return _totalRows;
} set
{
_totalRows = value;
}
} //绘制边界
private void GridFrameGizmo(int cols, int rows)
{
Gizmos.DrawLine(new Vector3(,,),new Vector3(,rows*GridSize,) );
Gizmos.DrawLine(new Vector3(, , ), new Vector3(cols*GridSize,, ));
Gizmos.DrawLine(new Vector3(cols*GridSize, , ), new Vector3(cols*GridSize, rows * GridSize, ));
Gizmos.DrawLine(new Vector3(, rows*GridSize, ), new Vector3(cols*GridSize, rows * GridSize, ));
} //绘制内部线条
private void GridGizmos(int cols, int rows)
{
for (int i = ; i < cols; i++)
{
Gizmos.DrawLine(new Vector3(i*GridSize,,),new Vector3(i*GridSize,rows*GridSize,) );
} for (int j = ; j < rows; j++)
{
Gizmos.DrawLine(new Vector3(,j * GridSize, ), new Vector3(cols * GridSize, j * GridSize, ));
}
} //D使用unity默认的OnDrawGizmos方法来绘制Gzimos
private void OnDrawGizmos()
{
Color oldColor = Gizmos.color;//修改的这些属性都是静态属性,所以要在修改前保存其值,修改后再复原,防止后续使用该静态属性是修改后的
Matrix4x4 oldMatrix = Gizmos.matrix;//修改的这些属性都是静态属性,所以要在修改前保存其值,修改后再复原,防止后续使用该静态属性是修改后的
Gizmos.matrix = transform.localToWorldMatrix;//该语句可以为gizmos提供该transform位移,旋转,缩放等特性 Gizmos.color = _normalColor;
GridGizmos(_totalColumns,_totalRows);
GridFrameGizmo(_totalColumns,_totalRows); Gizmos.color = oldColor;//恢复修改后的静态属性
Gizmos.matrix = oldMatrix;//恢复修改后的静态属性
} private void OnDrawGizmosSelected()
{
Color oldColor = Gizmos.color;
Matrix4x4 oldMatrix = Gizmos.matrix;
Gizmos.matrix = transform.localToWorldMatrix; Gizmos.color = _selectedColor;
GridFrameGizmo(_totalColumns, _totalRows); Gizmos.color = oldColor;
Gizmos.matrix = oldMatrix; } /// <summary>
/// 将世界坐标转换为grid网格中的点坐标
/// </summary>
/// <param name="point">世界坐标</param>
/// <returns></returns>
public Vector3 WordToGridCoordinates(Vector3 point)
{
Vector3 gridPoint=new Vector3((int)((point.x-transform.position.x)/GridSize),(int)((point.y-transform.position.y)/GridSize),0.0f);
return gridPoint;
} /// <summary>
/// Grid网格中的位置转换为世界坐标坐标
/// </summary>
/// <param name="col">行值</param>
/// <param name="row">列值</param>
/// <returns></returns>
public Vector3 GridToWordCoordinates(int col,int row)
{
Vector3 wordPoint=new Vector3(transform.position.x+(col*GridSize/2.0f),transform.position.y+(row*GridSize/2.0f),0.0f);
return wordPoint;
}
/// <summary>
/// 坐标位置是否在网格边界内
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public bool IsInsideGridBounds(Vector3 point)
{
float minX = transform.position.x;
float maxX = minX + _totalColumns*GridSize;
float minY = transform.position.y;
float maxY = minY + _totalRows*GridSize;
return (point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY);
} /// <summary>
/// 坐标位置是否在网格边界内
/// </summary>
/// <param name="point"></param>
/// <returns></returns> public bool IsInsideGridBounds(int col,int row)
{
return (col>=&&col<_totalColumns&&row>=&&row<=_totalRows);
}
}
}

2. 创建EditorUtil类,作为辅助工具类:

 using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEditor.SceneManagement; namespace RunAndJump.LevelCreator //为防止类名冲突,使用namespace时一个好的解决方案
{
public class EditorUtil
{ //创建新场景
public static void NewScene()
{
//该方法后续过时,被下面方法替代:EditorApplication.SaveCurrentSceneIfUserWantsTo();
EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();//当前场景有未保存的东西是,弹出对话框提醒是否保存当前场景
//该方法后续过时,被下面方法替代:EditorApplication.NewScene();
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
} //清空场景
public static void CleanScene()
{
GameObject[] allObjects = Object.FindObjectsOfType<GameObject>(); foreach (GameObject go in allObjects)
{
GameObject.DestroyImmediate(go);
}
} //创建新关卡
public static void NewLevel()
{
NewScene();
CleanScene(); //可以在创建新关卡时添加上必要的游戏对象
//add something... GameObject levelGo = new GameObject("Level");
levelGo.transform.position=Vector3.zero;
levelGo.AddComponent<Level>(); }
}
}

3. 创建MenuItems类,作为编辑器菜单工具类:

 using UnityEngine;
using System.Collections;
using UnityEditor; namespace RunAndJump.LevelCreator
{ //菜单项管理类,用来控制扩展方法在菜单项中显示
public class MenuItems
{
[MenuItem("Tools/LevelCreator/NewLevelScene %q") ]
private static void NewLevel()
{
EditorUtil.NewLevel();
}
}
}

4. 创建SnapToGridTest类,用来测试Leve类中方法:

 using UnityEngine;
using System.Collections;
using RunAndJump; [ExecuteInEditMode]//在editor场景模式下不用运行就调用
public class SnapToGridTest : MonoBehaviour { // Update is called once per frame
void Update ()
{
print(name+" in level");
Vector3 gridCoord = Level.Instance.WordToGridCoordinates(transform.position);
transform.position = Level.Instance.GridToWordCoordinates((int) gridCoord.x, (int) gridCoord.y);
} private void OnDrawGizmos()
{
print("gizoms");
Color oldColor = Gizmos.color;
Gizmos.color = (Level.Instance.IsInsideGridBounds(transform.position)) ? Color.green : Color.red;
Gizmos.DrawCube(transform.position,Vector3.one*Level.GridSize);
Gizmos.color = oldColor;
}
}

效果:

我们通过MenuItems创建的菜单调用EditorUtil中创建场景的方法,场景中在OnDrawGizoms方法中绘制出自己的网格。现在创建一个空物体为其绑上SnapToGridTest脚本用来验证level中用来对齐坐标到网格和验证是否出界的方法。

Unity 编辑器扩展 Chapter2—Gizmos-LMLPHP

05-11 15:46