Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Use Custom Texture with Human Stencil

Discussion in 'AR' started by cjensen1, Jul 22, 2019.

  1. cjensen1

    cjensen1

    Joined:
    Oct 23, 2016
    Posts:
    6
    Hey Everyone,

    I had a real tough time figuring out how to replace the ARKit3 human stencil with a custom texture, but I wrote a shader to make it possible. Thought I'd share it with everyone else on this forum.

     Shader "Unlit/AlphaMask" {
    Properties {
    _MainTex ("Base (RGB)", 2D) = "white" {}
    _AlphaTex ("Alpha mask (R)", 2D) = "white" {}
    _Angle ("Angle", Range(-5.0, 5.0)) = 0.0
    }

    SubShader {
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    LOD 100

    ZWrite Off
    Blend SrcAlpha OneMinusSrcAlpha

    Pass {
    CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag

    #include "UnityCG.cginc"

    struct appdata_t {
    float4 vertex : POSITION;
    float2 texcoord : TEXCOORD0;
    };

    struct v2f {
    float4 vertex : SV_POSITION;
    half2 texcoord : TEXCOORD0;
    };

    float _Angle;

    sampler2D _MainTex;
    sampler2D _AlphaTex;

    float4 _MainTex_ST;

    v2f vert (appdata_t v)
    {
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);

    // Pivot
    float2 pivot = float2(0.5, 0.5);
    // Rotation Matrix
    float cosAngle = cos(_Angle);
    float sinAngle = sin(_Angle);
    float2x2 rot = float2x2(cosAngle, -sinAngle, sinAngle, cosAngle);

    // Rotation consedering pivot
    float2 uv = v.texcoord.xy - pivot;
    o.texcoord = mul(rot, uv);
    o.texcoord += pivot;

    return o;
    }

    fixed4 frag (v2f i) : SV_Target
    {
    fixed4 col = tex2D(_MainTex, i.texcoord);
    fixed4 col2 = tex2D(_AlphaTex, float2(i.texcoord.x, 1 - i.texcoord.y));

    return fixed4(col.r, col.g, col.b, col2.r);
    }
    ENDCG
    }
    }

    }