如何获取ShaderGraph制作的Gerstner波浪高度以实现浮力?
Gerstner波浪C#高度计算与ShaderGraph同步实现方案
核心问题拆解
要让WaveManager.GetWaveHeight()返回和ShaderGraph中4层Gerstner波浪一致的高度,本质是把Shader里的GPU并行计算逻辑,复刻成C#的CPU串行计算逻辑,关键是严格对齐每层波浪的参数和计算步骤。
步骤1:提取ShaderGraph中的波浪参数
从你的ShaderGraph子图中,为每一层波浪提取以下核心参数:
- 归一化的方向向量(Wave Direction)
- 振幅(Amplitude)
- 波长(Wavelength)
- 相位移动速度(Speed,控制波浪流动的快慢)
把这些参数整理成可复用的结构体:
public struct GerstnerWave { public Vector2 direction; public float amplitude; public float wavelength; public float speed; }
步骤2:实现单波浪高度计算
Gerstner波浪的高度计算公式在Shader和C#中完全一致,单波浪对目标位置的高度贡献代码:
private float CalculateSingleWaveHeight(GerstnerWave wave, Vector3 position, float time) { Vector2 posXZ = new Vector2(position.x, position.z); float phase = Mathf.PI * 2f * Vector2.Dot(wave.direction, posXZ) / wave.wavelength + wave.speed * time; return wave.amplitude * Mathf.Cos(phase); }
步骤3:累加4层波浪的总高度
在WaveManager中维护存储4层波浪参数的列表,然后在GetWaveHeight()中遍历累加:
public List<GerstnerWave> waves; // 在Inspector中填入和ShaderGraph完全一致的4层参数 public float GetWaveHeight(Vector3 position) { float totalHeight = 0f; float currentTime = Time.time; // 必须和Shader中使用的时间变量同步(比如Shader用_Time.y则对应此值) foreach (var wave in waves) { totalHeight += CalculateSingleWaveHeight(wave, position, currentTime); } return totalHeight; }
关键对齐点
- 时间同步:Shader和C#的时间基准必须完全一致,若Shader有自定义时间缩放,C#需同步调整
- 参数一致性:方向向量必须归一化,振幅、波长数值要和ShaderGraph完全匹配,单位需和场景坐标统一
- 计算精度:C#的
Mathf.Cos、Vector2.Dot与Shader中HLSL的对应函数精度一致,无需额外处理
内容的提问来源于stack exchange,提问作者Magnality
相关产品推荐
相关产品推荐

