Hello everyone
I would like to start by saying i am new to shaders. Anyways, i have written some simple outline shader for UI.Image component to use. It simply makes the original image disappear and draws an outline around it.
However, when i apply it to an image, it gets drawn even outside of its viewport parent, which is a big issue. I tried standard unity shaders and same thing happens. I guess it is an issue with shaders? How can i make it so that it doesnt get drawn outside of its viewport.
Here is the code for shader:
Shader "Unlit/Outline"
{
Properties
{
[PerRendererData] _MainTex ("Texture", 2D) = "white" {}
_Thickness ("Thickness", Range(0.0, 0.15)) = 0.05
_Color ("Color", Color) = (1, 1, 1, 1)
}
SubShader
{
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
"PreviewType"="Plane"
"CanUseSpriteAtlas"="True"
}
Cull Off
Lighting Off
ZWrite Off
ZTest [unity_GUIZTestMode]
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Thickness;
float4 _Color;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float minAlpha = 0.85;
// sample the texture
if (tex2D(_MainTex, i.uv).a > minAlpha)
return fixed4(0, 0, 0, 0);
float2 myOffSet = float2(_Thickness * 0.7071, _Thickness * 0.7071);
float2 myOffSetV = float2(0, _Thickness);
float2 myOffSetH = float2(_Thickness, 0);
float alphaStrength = 0;
alphaStrength = tex2D(_MainTex, i.uv + (myOffSetV * 1)).a
+ tex2D(_MainTex, i.uv + (myOffSetV * -1)).a
+ tex2D(_MainTex, i.uv + (myOffSetH * 1)).a
+ tex2D(_MainTex, i.uv + (myOffSetH * -1)).a
+ tex2D(_MainTex, i.uv + (myOffSet * (1, 1))).a
+ tex2D(_MainTex, i.uv + (myOffSet * (-1, 1))).a
+ tex2D(_MainTex, i.uv + (myOffSet * (1, -1))).a
+ tex2D(_MainTex, i.uv + (myOffSet * (-1, -1))).a;
if (alphaStrength > 1.0)
alphaStrength = 1.0;
return fixed4(_Color.r, _Color.g, _Color.b, _Color.a * alphaStrength - tex2D(_MainTex, i.uv).a);
}
ENDCG
}
}
}