1. 程式人生 > >UnityShader 簡單水的效果,以及海岸效果

UnityShader 簡單水的效果,以及海岸效果

這裡寫圖片描述
1.下面主要拿一張類似上面的底層圖片,通過控制外部引數 xScroll Speed ,yScroll Speed來調整水流速度引數。

Shader "SeaShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
         _ScrollXSpeed ("X Scrll Speed", Range(0, 10)) = 2
        _ScrollYSpeed ("Y Scrll Speed", Range(0, 10)) = 2
    }
    SubShader
    {
        Tags { "RenderType"
="Opaque" } LOD 200 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag // make fog work #pragma multi_compile_fog #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct
v2f { float2 uv : TEXCOORD0; UNITY_FOG_COORDS(1) float4 vertex : SV_POSITION; }; sampler2D _MainTex; float4 _MainTex_ST; fixed _ScrollXSpeed; fixed _ScrollYSpeed; v2f vert (appdata v) { v2f o; o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); fixed
xScrollValue = _ScrollXSpeed * _Time; fixed yScrollValue = _ScrollYSpeed * _Time; v.uv += fixed2(xScrollValue, yScrollValue); o.uv = TRANSFORM_TEX(v.uv, _MainTex); UNITY_TRANSFER_FOG(o,o.vertex); return o; } fixed4 frag (v2f i) : SV_Target { // sample the texture fixed4 col = tex2D(_MainTex, i.uv); // apply fog UNITY_APPLY_FOG(i.fogCoord, col); return col; } ENDCG } } }
  1. 建立海岸效果起先要有一個模型類似環島的如下橙色區域,以及類似下面的漸變圖片。
    . 這裡寫圖片描述
    這裡寫圖片描述

  2. 圖片屬性要調整如下
    這裡寫圖片描述

5.好了用程式碼控制UV偏移,放在海岸模型上,海岸模型shader為上面截圖的透明shader。

using UnityEngine;
using System.Collections;

public class water : MonoBehaviour
{

    [Header("水波速度")]
    public float scrollSpeed;
    private Vector2 offset;
    private bool isBack;

    // Scroll main texture based on time
    //根據時間滾動主紋理

    void Update()
    {
        offset = gameObject.GetComponent<Renderer>().material.mainTextureOffset;
        if (!isBack)
        {
            offset.y += scrollSpeed * Time.deltaTime;
            if (offset.y >= 0.15)
                isBack = true;
        }
        else
        {
            offset.y -= scrollSpeed * Time.deltaTime;
            if (offset.y <= -0.2 )
                isBack = false;
        }
        gameObject.GetComponent<Renderer>().material.mainTextureOffset = offset;

    }
}
  1. 裡面有一個問題要注意是,海岸圖片要設定為CLAMP 屬性,否則會一直白邊。