Hi guys,
I’m trying to write my first shader which goal is to set the alpha value according to a target distance. I have 2 files, one for the shader and one for a script that set the new target position inside an Update method. It seems that whatever my target position is the alpha value is never updated. I’m pretty it’s all my fault but I need some help to point me in the right direction.
The shader script :
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "Custom/AlphaDependingDistance"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_MinAlpha("Alpha min", Float) = 0.25
_MaxAlpha("Alpha max", Float) = 1.
_MinDistance("Distance min", Float) = 100.
_MaxDistance("Distance max", Float) = 200.
}
SubShader
{
Tags {"Queue"="Transparent" "RenderType"="Transparent" }
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float4 worldPos : TEXCOORD1;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert(appdata_base v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
return o;
}
float _MinAlpha;
float _MaxAlpha;
float _MinDistance;
float _MaxDistance;
float4 _Target;
fixed4 frag(v2f i) : SV_Target {
fixed4 col = tex2D(_MainTex, i.uv);
//Compute distance
//float dist = distance(i.worldPos, _WorldSpaceCameraPos);
float dist = distance(i.worldPos, _Target);
//Clamp distance
dist = clamp(dist,_MinDistance,_MaxDistance);
//Compute distance ratio
dist = (dist - _MinDistance) / (_MaxDistance - _MinDistance);
//Compute Alpha
col.a = _MinAlpha + (_MaxAlpha - _MinAlpha) * dist;
return col;
}
ENDCG
}
}
}
The MonoBehavior script :
public class AlphaDependingScript : MonoBehaviour {
public Transform target;
private Material m;
void Awake(){
m = this.gameObject.GetComponent<SpriteRenderer> ().sharedMaterial;
}
void Update(){
if (m != null) {
m.EnableKeyword("_Target");
m.SetVector("_Target", target.position);
}
}
}
I tried to declare _Target as a Vector at first but it changed nothing. I don’t know if the issue is about the distance calculation or about updating the target position or … I’m having trouble to figured what’s happening because I have no clue how to set some “debug” in the shader code.
Any help would be great.
Thanks