- Home /
Question by
natemiddleman · Sep 01, 2016 at 05:46 AM ·
shadershadersshader programmingshader writing
Shader Help
I am trying to make a simple shader that makes objects darker the farther away they are from the camera in the z axis. I am completely new to shaders, but after a lot of searching, I thought I had figured it out by doing
"color.rgb *= distance(_WorldSpaceCameraPos.z, mul(_Object2World, IN.vertex).z)/30;"
What this ended up doing was making every object the same shade depending on the height of the camera instead of the distance from the camera. Can someone please let me know where I went wrong?
Shader "Custom/CustomSpriteShader"
{
Properties
{
[PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
_Color("Tint", Color) = (1,1,1,1)
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
"PreviewType" = "Plane"
"CanUseSpriteAtlas" = "True"
}
Cull Off
Lighting Off
ZWrite Off
Blend One OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
fixed4 _Color;
v2f vert(appdata IN)
{
v2f OUT;
OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color * _Color;
return OUT;
}
sampler2D _MainTex;
sampler2D _AlphaTex;
fixed4 SampleSpriteTexture(float2 uv)
{
fixed4 color = tex2D(_MainTex, uv);
return color;
}
fixed4 frag(v2f IN) : SV_Target
{
fixed4 color = SampleSpriteTexture(IN.texcoord) * IN.color;
color.rgb *= distance(_WorldSpaceCameraPos.z, mul(_Object2World, IN.vertex).z)/30;
return color;
}
ENDCG
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612091938im_/https://answers.unity.com/themes/thub/images/avi.jpg)