Search code examples
unity-game-enginetextures

Unity - Simulate a % filled cube with a texture


i want to simulate a cube filled with "water". I want to implement a very basic solution using a texture or image, no particle animation or something. To be more clear ,if the cube is filled 40% i'd like to see the gameobject with 40% color and 60% white. Unfortunately i'm a Newbie of Unity too.. Can someone give me some hints or point me to a kind of tutorial that can help me?

Thanks for your time and answers


Solution

  • One option is to use a cutout shader. Below is an example:

    Shader "Fade/Diffuse"
     {
         Properties
         {
             _Color ("Main Color", Color) = (1,1,1,1)
             _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
             _FadeMap ("Fade Map", 2D) = "white" {}
             _Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
         }
    
         SubShader
         {
             Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Opaque"}
             LOD 300
             Cull Off
             CGPROGRAM
             #pragma surface surf Standard
    
             sampler2D _MainTex;
             sampler2D _FadeMap;
             float _Cutoff;
             fixed4 _Color;
    
             struct Input
             {
                 float2 uv_MainTex;
             };
    
             void surf (Input IN, inout SurfaceOutputStandard o)
             {
                 fixed4 diffuse = tex2D(_MainTex, IN.uv_MainTex) * _Color;
                 fixed4 fadeSample = tex2D(_FadeMap, IN.uv_MainTex);
    
                 bool cut = (fadeSample.r + fadeSample.g + fadeSample.b)/3.0 < _Cutoff ? false : true;
                 o.Albedo = cut ? diffuse.rgb : float3(1,1,1);
    
    
             }
             ENDCG
         }
    
         FallBack "Transparent/Cutout/Diffuse"
     }
    

    This shader takes 2 textures:

    • Color
    • Grayscale texture where black = cutout

    One important thing about this solution is the UV mapping of your cube. If you use the standard built-in cube, you will notice that the "water level" also animates on the top and bottom of the cubes and also in the wrong direction on some of the sides. You will have to make your own cube with UVs that map the top of the cube to the black part of your fade map.

    Here is the final result:

    Here is the final result