Unity sharedMesh 制作波浪

这里写图片描述

通过改变网格的顶点坐标来实现波浪效果

波浪图片随便网上找一张,然后丢给材质球的 Albedo 属性中。
然后将材质球和脚本,拖入 Plane 游戏对象。

这里写图片描述

修改材质球的 Main Maps 参数中的 Tiling 值,使纹理贴图在XY平面上重复多次(这样可以使用较小的贴图,从而降低所需内存和游戏大小)。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 叠加方式
/// </summary>
public enum Superposition {
    /// <summary>
    /// 周期叠加
    /// </summary>
    Cycle,
    /// <summary>
    /// 震幅叠加
    /// </summary>
    Amplitude 
}

public class WaterWave : MonoBehaviour {

    /// <summary>
    /// 水波震幅
    /// </summary>
    public float amplitude = 1f;
    /// <summary>
    /// 波动的速度
    /// </summary>
    public float speed = 3f;
    /// <summary>
    /// 震幅叠加方式
    /// </summary>
    public Superposition superposition = Superposition.Cycle;

    /// <summary>
    /// 模型网格
    /// </summary>
    private Mesh sharedMesh;
    /// <summary>
    /// 网格的初始顶点坐标数组
    /// </summary>
    private Vector3[] baseVertex;  
    /// <summary>
    /// 网格修改后的顶点坐标数组
    /// </summary>
    private Vector3[] nowVertex;  

    // Use this for initialization  
    void Start ()   
    {  
        sharedMesh = GetComponent<MeshFilter>().sharedMesh;  
        baseVertex = sharedMesh.vertices;  
        nowVertex = sharedMesh.vertices;  
    }  

    // Update is called once per frame  
    void Update ()   
    {  
        for (int i = 0; i < baseVertex.Length; i++) {  
            nowVertex [i] = baseVertex [i];  

            switch (superposition) {  
            case Superposition.Cycle:
                nowVertex [i].y += Mathf.Sin (Time.time * speed + baseVertex [i].x + baseVertex [i].z) * amplitude;  
                break;
            case Superposition.Amplitude:
                nowVertex [i].y += Mathf.Sin (Time.time * speed + baseVertex [i].x) * amplitude + Mathf.Sin (Time.time * speed + baseVertex [i].z) * amplitude;
                break;
            }  
        }
        sharedMesh.vertices = nowVertex;  
    }  
}

注意:sharedMesh是公用的,是引用传递。而mesh是值传递,是各自拥有的实例。这里如果使用mesh会报内存泄漏(memory leak)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值