Shadow.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. using System.Collections;
  3. [ExecuteInEditMode]
  4. public class Shadow : MonoBehaviour {
  5. public Camera m_ShadowCamera;
  6. private RenderTexture m_RT;
  7. public Material m_Mat;
  8. void Start()
  9. {
  10. GetComponent<Projector>().enabled = true;
  11. //创建一个纹理,用来捕获照相机的看到的(该纹理既为我们需要的影子的源纹理)
  12. m_RT = new RenderTexture(512, 512, 0, RenderTextureFormat.ARGB32);
  13. m_RT.anisoLevel = 8;
  14. m_ShadowCamera.targetTexture = m_RT;
  15. //将上面的纹理传入材质球中,用来将它处理为影子
  16. m_Mat.SetTexture("_MainTex", m_RT);
  17. }
  18. void LateUpdate()
  19. {
  20. //实时将生成影子需要的纹理的照相机的矩阵传入材质球,这两个矩阵在下面的着色器代码中使用
  21. m_Mat.SetTexture("_MainTex", m_RT);
  22. m_Mat.SetMatrix("_WorldToCameraMatrix", m_ShadowCamera.worldToCameraMatrix);
  23. m_Mat.SetMatrix("_ProjectionMatrix", m_ShadowCamera.projectionMatrix);
  24. }
  25. void OnDrawGizmos()
  26. {
  27. if (!Application.isEditor)
  28. return;
  29. m_Mat.SetTexture("_MainTex", m_RT);
  30. //实时将生成影子需要的纹理的照相机的矩阵传入材质球,这两个矩阵在下面的着色器代码中使用
  31. m_Mat.SetMatrix("_WorldToCameraMatrix", m_ShadowCamera.worldToCameraMatrix);
  32. m_Mat.SetMatrix("_ProjectionMatrix", m_ShadowCamera.projectionMatrix);
  33. }
  34. public void OpenShadow()
  35. {
  36. if (m_ShadowCamera.enabled)
  37. {
  38. m_ShadowCamera.enabled = false;
  39. GetComponent<Projector>().enabled = false;
  40. }
  41. else
  42. {
  43. m_ShadowCamera.enabled = true;
  44. GetComponent<Projector>().enabled = true;
  45. }
  46. }
  47. }