Unity Shader 繪制點直線網格等基本圖形


利用 Plane 映射到屏幕上的像素坐標作為繪制圖形的輸入參數。

Shader003 代碼:

Shader "Custom/Shader003" {

	Properties {
		// 在 Properties 中添加要繪制的點位置信息
		_Point1("Point1",vector) = (100,100,0,0)
		_Point2("Point2",vector) = (200,200,0,0)
		// 在 Properties 中添加要繪制的直線上兩點位置及直線寬度
		_LP1("linePoint1",vector) = (300,100,0,0)
		_LP2("linePoint2",vector) = (600,400,0,0)
		_LineWidth("LineWidth", range(1,20)) = 2.0
	}

	SubShader {
		Pass {
			CGPROGRAM

			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"

			struct appdata{
				float4 vertex : POSITION;
			};

			struct v2f{
				float4 vertex : SV_POSITION;
			};

			float4 _Point1;
			float4 _Point2;
			float4 _LP1;
			float4 _LP2;
			float _LineWidth;

			v2f vert(appdata v){
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				return o;
			}

			fixed4 frag(v2f i) : SV_Target {

				// 繪制圓形, 此處半徑使用了固定值 1000 和 500, 當然也可以寫成可調的參數
				if(pow((i.vertex.x - _Point1.x),2) + pow((i.vertex.y - _Point1.y),2) < 1000){
					return fixed4(0,1,0,1);
				}

				if(pow((i.vertex.x - _Point2.x),2) + pow((i.vertex.y - _Point2.y),2) < 500) {
					return fixed4(1,0,0,1);
				}

				// 繪制直線上兩點
				if(pow((i.vertex.x - _LP1.x),2) + pow((i.vertex.y - _LP1.y),2) < 100){
					return fixed4(0,0,1,1);
				}

				if(pow((i.vertex.x - _LP2.x),2) + pow((i.vertex.y - _LP2.y),2) < 100){
					return fixed4(0,0,1,1);
				}

				// 計算點到直線的距離
				float d = abs((_LP2.y - _LP1.y) * i.vertex.x + (_LP1.x - _LP2.x) * i.vertex.y + _LP2.x * _LP1.y - _LP2.y * _LP1.x)
				/ sqrt(pow(_LP2.y - _LP1.y , 2) + pow(_LP1.x - _LP2.x ,2));

				// 小於或者等於線寬的一半時, 屬於直線范圍
				if(d<=_LineWidth/2){
					return fixed4(0.8,0.2,0.5,1);
				}

				// 繪制網格直線
				if((unsigned int)i.vertex.x % (unsigned int)(0.25 * _ScreenParams.x) == 0){
					return fixed4(0,0,1,1);
				}

				if((unsigned int) i.vertex.y % (unsigned int)(0.1 * _ScreenParams.x) == 0){
					return fixed4(0,0,1,1);
				}

				// 默認返回白色
				return fixed4(1,1,1,1);
			}
			ENDCG
		}
	}
}

根據兩點繪制直線。問題轉化為計算哪些點在直線的線寬范圍內。首先利用直線的兩點式方程,過 (x1,x2) 和 (y1,y2) 的直線上任意點 (x,y) 滿足公式 : 即,

根據點到直線的距離公式,某一點 (x0,y0) 到上述直線的距離為

結果 :

End.

→ 源碼 GitHub


免責聲明!

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



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