Advertisement
Edwarddv

Draw Quad Stack for Clouds

Sep 25th, 2018
1,453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class DrawCloudsExample : MonoBehaviour {
  4.  
  5.     public int horizontalStackSize = 20;
  6.     public float cloudHeight = 1f;
  7.     public Mesh quadMesh;
  8.     public Material cloudMaterial;
  9.     float offset;
  10.  
  11.     public int layer;
  12.     public Camera camera;
  13.     private Matrix4x4 matrix;
  14.     private Matrix4x4[] matrices;
  15.     public bool castShadows = false;
  16.     public bool useGpuInstancing = false;
  17.  
  18.     void Update()
  19.     {
  20.  
  21.         cloudMaterial.SetFloat("_midYValue", transform.position.y);
  22.         cloudMaterial.SetFloat("_cloudHeight", cloudHeight);
  23.  
  24.         offset = cloudHeight / horizontalStackSize / 2f;
  25.         Vector3 startPosition = transform.position + (Vector3.up * (offset * horizontalStackSize / 2f));
  26.  
  27.         if (useGpuInstancing) // initialize matrix array
  28.         {
  29.             matrices = new Matrix4x4[horizontalStackSize];
  30.         }
  31.  
  32.         for (int i = 0; i < horizontalStackSize; i++)
  33.         {
  34.             matrix = Matrix4x4.TRS(startPosition - (Vector3.up * offset * i), transform.rotation, transform.localScale);
  35.  
  36.             if (useGpuInstancing)
  37.             {
  38.                 matrices[i] = matrix; // build the matrices array if using GPU instancing
  39.             }
  40.             else
  41.             {
  42.                 Graphics.DrawMesh(quadMesh, matrix, cloudMaterial, layer, camera, 0, null, castShadows, false, false); // otherwise just draw it now
  43.             }
  44.         }
  45.  
  46.         if (useGpuInstancing) // draw the built matrix array
  47.         {
  48.             UnityEngine.Rendering.ShadowCastingMode shadowCasting = UnityEngine.Rendering.ShadowCastingMode.Off;
  49.             if (castShadows)
  50.                 shadowCasting = UnityEngine.Rendering.ShadowCastingMode.On;
  51.  
  52.             Graphics.DrawMeshInstanced(quadMesh, 0, cloudMaterial, matrices, horizontalStackSize, null, shadowCasting, false, layer, camera);
  53.  
  54.         }
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement