您的位置:首页 > 移动开发 > Unity3D

UnityEditor 用Gizmos画出类似NGUI,UIPanel的矩形框

2015-11-16 22:34 435 查看
using UnityEngine;

using System.Collections;

using UnityEditor;

public class CamDrawGizmo : Editor {

[DrawGizmo(GizmoType.Selected)]

static void DrawRect(Transform transform, GizmoType gizmoType)

{

float z = transform.position.z - Camera.main.transform.localPosition.z;

//摄像机的位置

Vector3 camPos = Camera.main.transform.position;

//transform的位置

Vector3 transformPos = transform.position;

float height = z*2.0f*Mathf.Tan(Camera.main.GetComponent<Camera>().fieldOfView/2.0f*Mathf.Deg2Rad);

float width = height * Camera.main.GetComponent<Camera>().aspect;

Vector3[] corners = new Vector3[4];

if (transform.parent != null) {

//确保GameObject移动的时候,矩形框不跟着移动,所以矩形框的中心点和Camer是对齐的,

//我现在要做的是,在矩形框的4个角上,标注出位置,这个位置指:只要在GameObject的Position中输入这个位置,

//那么GameObject就会移出画面(对于不同的Z)

//所以这个时候这4个角上的位置,要转化为父节点下的相对坐标点

//transform.parent.worldToLocalMatrix(point) == transform.parent.InverseTransformPoint(point)

//transform.parent.localToWorldMatrix.MultiplyPoint(point) == transform.parent.TransformPoint(point);

corners[0] = (transform.parent.worldToLocalMatrix.MultiplyPoint (new Vector3 (camPos.x - width / 2, camPos.y - height / 2, transformPos.z)));

corners[1] = (transform.parent.worldToLocalMatrix.MultiplyPoint (new Vector3 (camPos.x - width / 2, camPos.y + height / 2, transformPos.z)));

corners[2] = (transform.parent.worldToLocalMatrix.MultiplyPoint (new Vector3 (camPos.x + width / 2, camPos.y + height / 2, transformPos.z)));

corners[3] = (transform.parent.worldToLocalMatrix.MultiplyPoint (new Vector3 (camPos.x + width / 2, camPos.y - height / 2, transformPos.z)));

}

else{

corners[0] = new Vector3 (camPos.x - width / 2, camPos.y - height / 2, transformPos.z);

corners[1] = new Vector3 (camPos.x - width / 2, camPos.y + height / 2, transformPos.z);

corners[2] = new Vector3 (camPos.x + width / 2, camPos.y + height / 2, transformPos.z);

corners[3] = new Vector3 (camPos.x + width / 2, camPos.y - height / 2, transformPos.z);

}

//

for (int i = 0; i<4; i++) {

corners[i].z = transformPos.z;

}

Vector3[] lablePos = new Vector3[4];

lablePos[0] = new Vector3 (camPos.x - width / 2, camPos.y - height / 2, transformPos.z);

lablePos[1] = new Vector3 (camPos.x - width / 2, camPos.y + height / 2, transformPos.z);

lablePos[2] = new Vector3 (camPos.x + width / 2, camPos.y + height / 2, transformPos.z);

lablePos[3] = new Vector3 (camPos.x + width / 2, camPos.y - height / 2, transformPos.z);

for (int i = 0; i<4; i++) {

//4个角上的确切位置是相对于世界坐标系的,但是标注的string是表示的相对于父节点的坐标

Handles.Label(lablePos[i], corners[i].ToString ());

}

Gizmos.color = Color.green;

//rect的位置

Vector3 rectPos = camPos;

rectPos.z = transformPos.z;

Gizmos.DrawWireCube(rectPos, new Vector3(width, height, 0));

}

}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: