Advertisement
Staggart

Scale Wave Height By Distance

Jun 16th, 2025
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System;
  2. using UnityEngine;
  3.  
  4. public class ScaleWaveHeightByDistance : MonoBehaviour
  5. {
  6.     public Transform player;
  7.     public Material waterMaterial;
  8.  
  9.     [Header("Distance gradient")]
  10.     public float minDistance = 100f;
  11.     public float maxDistance = 500f;
  12.    
  13.     [Header("Wave scale")]
  14.     [Min(0f)]
  15.     public float minHeight = 0f;
  16.     [Min(0.1f)]
  17.     public float maxHeight = 1f;
  18.  
  19.     float originalHeight;
  20.     private static readonly int _WaveHeight = Shader.PropertyToID("_WaveHeight");
  21.    
  22.     void Start()
  23.     {
  24.         if (waterMaterial == null || waterMaterial.HasProperty(_WaveHeight) == false)
  25.         {
  26.             this.enabled = false;
  27.             throw new Exception("Water material is missing or not using the Stylized Water 3 shader...");
  28.         }
  29.        
  30.         originalHeight = waterMaterial.GetFloat(_WaveHeight);
  31.     }
  32.    
  33.     private void Update()
  34.     {
  35.         float distance = Vector3.Distance(this.transform.position, player.position);
  36.        
  37.         float t = (distance - minDistance) / (maxDistance - minDistance);
  38.        
  39.         waterMaterial.SetFloat(_WaveHeight, Mathf.Lerp(minHeight, maxHeight, t));
  40.     }
  41.  
  42.     private void OnDestroy()
  43.     {
  44.         waterMaterial.SetFloat(_WaveHeight, originalHeight);
  45.     }
  46.  
  47.     private void OnDrawGizmosSelected()
  48.     {
  49.         #if UNITY_EDITOR
  50.         UnityEditor.Handles.color = Color.yellow;
  51.         UnityEditor.Handles.DrawWireDisc(this.transform.position, Vector3.up, minDistance);
  52.         UnityEditor.Handles.DrawWireDisc(this.transform.position, Vector3.up, maxDistance);
  53.         #endif
  54.     }
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement