今天用UnityShader脚本来制作Shader。
先上最终效果图:
然后,还是直接上源码吧:
Shader "MyShader/SS_5"
{
Properties
{
_X("X",float) = 0
_Y("Y",float) = 0
_Width("Width",float) = 1
_Height("Height",float)=1
_MainTex("Texture", 2D) = ""{}
_Color("Color",Color) = (1,1,1,1)
[Enum(SIN,0,COS,1,TAN,2,EXP,3,LOG,4,PLOGP,5,Custom,6)] _Type("CurveType", Float) = 0
}
SubShader
{
Tags{
"RenderType" = "Transparent"
}
CGINCLUDE
#include "UnityCG.cginc"
float _X;
float _Y;
float _Width;
float _Height;
Float _Type;
fixed4 _Color;
sampler2D _MainTex;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 normal : NORMAL;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
float4 worldPos : TEXCOORD1;
float3 normal : TEXCOORD2;
};
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
o.normal = v.normal;
return o;
}
fixed Fun0(fixed _x) {
return sin(_x);
}
fixed Fun1(fixed _x) {
return cos( _x ) ;
}
fixed Fun2(fixed _x) {
return tan(_x);
}
fixed Fun3(fixed _x) {
return exp(_x);
}
fixed Fun4(fixed _x) {
return log(_x);
}
//熵公式
fixed Fun5(fixed _x) {
return -_x*log(_x);
}
fixed4 frag(v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
fixed x = _Time.y+_Width * (i.uv.x-0.5) - _X*0.01;//减0.5是为了居中;乘0.01是为了将坐标系单位放大100倍
fixed y = Fun0(x);
if (_Type == 1) {
y = Fun1(x);
}
else if (_Type == 2) {
y = Fun2(x);
}
else if (_Type == 3) {
y = Fun3(x);
}
else if (_Type ==4) {
y = Fun4(x);
}
else if (_Type ==5) {
y = Fun5(x);
}else if (_Type ==6) {
y =abs(1+Fun0(3*x)*Fun1(10*x)*Fun0(3*x)/Fun1(2*x))-1;
}
fixed temp = i.uv.y;//因为要先绘制曲线,之后绘制坐标轴时会用到i.uv.y,所以先保存下来
i.uv.y += -_Height*(y+_Y)*0.01;//乘0.01是为了将坐标系单位放大100倍
fixed w = abs(1 / (100*(i.uv.y-0.5)));//减0.5是为了居中
fixed4 wave=fixed4(w,w,w,1);
if(wave.x+wave.y+wave.z>6) //加这行是为了过滤掉,不过不加的话效果更好
col +=wave*_Color; //先绘制曲线
w= abs(1 / (7000 * (temp - 0.5)));//除7000是为了让轴线更细
col+= (fixed4(w, w, w, 1));//再绘制X坐标轴
w = abs(1/(7000*(i.uv.x - 0.5)));
col += (fixed4(w, w, w, 1));//再绘制Y坐标轴
return col;
}
ENDCG
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDCG
}
}
}
然后效果图的参数:
这个脚本还能扩展,修改波形的函数,或者直接通过cs脚本控制波形等等。