Unity之屏幕畫線


 

using UnityEngine;
using System.Collections;

public class DrawRectangle : MonoBehaviour {

public Color rectColor = Color.green;


private Material rectMat = null;//畫線的材質 不設定系統會用當前材質畫線 結果不可控

// Use this for initialization

void Start () {

rectMat = new Material( "Shader \"Lines/Colored Blended\" {" +

"SubShader { Pass { " +

" Blend SrcAlpha OneMinusSrcAlpha " +

" ZWrite Off Cull Off Fog { Mode Off } " +

" BindChannels {" +

" Bind \"vertex\", vertex Bind \"color\", color }" +

"} } }" );//生成畫線的材質

rectMat.hideFlags = HideFlags.HideAndDontSave;

rectMat.shader.hideFlags = HideFlags.HideAndDontSave; 

}


void Update () {
}



void OnPostRender() {//畫線這種操作推薦在OnPostRender()里進行 而不是直接放在Update,所以需要標志來開啟

Rect rect0 = new Rect(0,0,0,0);


drawRect(rect0);

}

 

void drawRect(Rect rect0){
if (! rectMat) 
return;
GL.PushMatrix();//保存攝像機變換矩陣
rectMat.SetPass( 0 );

GL.LoadPixelMatrix();//設置用屏幕坐標繪圖

// GL.Begin(GL.QUADS);

// GL.Color( new Color(rectColor.r,rectColor.g,rectColor.b,0.1f) );//設置顏色和透明度,方框內部透明

// GL.Vertex3( 0,0,0);

// GL.Vertex3( Screen.width/2,0,0);

// GL.Vertex3( Screen.width/2,Screen.height/2,0 );

// GL.Vertex3( 0,Screen.height/2,0 );

// GL.End();
float startX = rect0.x;
float startY = rect0.y;
float endX = rect0.xMax;
float endY = rect0.yMax;

GL.Begin(GL.LINES);

GL.Color(rectColor);//設置方框的邊框顏色 邊框不透明

GL.Vertex3( startX,startY,0);
GL.Vertex3( endX,startY,0);

GL.Vertex3( endX,startY,0);
GL.Vertex3( endX,endY,0 );

GL.Vertex3( endX,endY,0 );
GL.Vertex3( startX,endY,0 );

GL.Vertex3( startX,endY,0 );
GL.Vertex3( startX,startY,0);

GL.End();
// GL.Begin(GL.LINES);
// GL.Vertex3(0, 0, 0);
// GL.Vertex3(Screen.width, Screen.height, 0);
// GL.End(); 
GL.PopMatrix();//恢復攝像機投影矩陣
}


void drawRects(Rect[] rects){
if (! rectMat) 
return;
GL.PushMatrix();//保存攝像機變換矩陣
rectMat.SetPass( 0 );

GL.LoadPixelMatrix();//設置用屏幕坐標繪圖

// GL.Begin(GL.QUADS);

// GL.Color( new Color(rectColor.r,rectColor.g,rectColor.b,0.1f) );//設置顏色和透明度,方框內部透明

// GL.Vertex3( 0,0,0);

// GL.Vertex3( Screen.width/2,0,0);

// GL.Vertex3( Screen.width/2,Screen.height/2,0 );

// GL.Vertex3( 0,Screen.height/2,0 );

// GL.End();
GL.Begin(GL.LINES);
for(int i = 0 ; i < rects.Length ; i++){

Rect rect0 = rects[i];
//Debug.Log(rect0);
float startX = rect0.x;
float startY = rect0.y;
float endX = rect0.xMax;
float endY = rect0.yMax;



GL.Color(rectColor);//設置方框的邊框顏色 邊框不透明

GL.Vertex3( startX,startY,0);
GL.Vertex3( endX,startY,0);

GL.Vertex3( endX,startY,0);
GL.Vertex3( endX,endY,0 );

GL.Vertex3( endX,endY,0 );
GL.Vertex3( startX,endY,0 );

GL.Vertex3( startX,endY,0 );
GL.Vertex3( startX,startY,0);


}
GL.End();
// GL.Begin(GL.LINES);
// GL.Vertex3(0, 0, 0);
// GL.Vertex3(Screen.width, Screen.height, 0);
// GL.End(); 
GL.PopMatrix();//恢復攝像機投影矩陣

}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM