ControlDisplacer.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace Lux_SRP_GrassDisplacement {
  6. [ExecuteInEditMode]
  7. public class ControlDisplacer : MonoBehaviour {
  8. public float maxDistance = 1.0f;
  9. public float fallOff = 2.0f;
  10. [Layer]
  11. public int layerMask = 0;
  12. [Space(5)]
  13. public bool DebugRay = true;
  14. private Transform trans;
  15. private Renderer rend;
  16. private MaterialPropertyBlock mpb;
  17. private RaycastHit hit;
  18. private float alpha;
  19. void OnEnable() {
  20. trans = this.GetComponent<Transform>();
  21. rend = this.GetComponent<Renderer>();
  22. mpb = new MaterialPropertyBlock();
  23. mpb.Clear();
  24. rend.SetPropertyBlock(mpb);
  25. }
  26. void OnDisable() {
  27. mpb.Clear();
  28. rend.SetPropertyBlock(null);
  29. }
  30. void Update() {
  31. var mask = 1 << layerMask;
  32. if (Physics.Raycast(trans.position, Vector3.down, out hit, maxDistance, mask )) {
  33. #if UNITY_EDITOR
  34. if(DebugRay) {
  35. Debug.DrawRay(transform.position, Vector3.down * hit.distance, Color.green);
  36. }
  37. #endif
  38. alpha = (float)(1.0 - Math.Pow(hit.distance / maxDistance, fallOff));
  39. mpb.SetFloat("_Alpha", alpha);
  40. rend.SetPropertyBlock(mpb);
  41. }
  42. else {
  43. #if UNITY_EDITOR
  44. if(DebugRay) {
  45. Debug.DrawRay(transform.position, Vector3.down * maxDistance, Color.red);
  46. }
  47. #endif
  48. if (alpha != 0.0f) {
  49. alpha = 0.0f;
  50. mpb.SetFloat("_Alpha", 0.0f);
  51. rend.SetPropertyBlock(mpb);
  52. }
  53. }
  54. }
  55. }
  56. }