了解shader的uv动画

发表于2018-06-28
评论5 8.4k浏览

本文主要介绍学习shaderuv动画,利用序列贴图来展示动画效果。

原理:shader变换UV采样序列帧贴图

下面是网上摘的一段shader代码:

Shader "Custom/NewSurfaceShader" {

 Properties {

    _Color ("Main Color", Color) = (1,1,1,1)

    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}

    _SizeX ("", Float) = 4 

    _SizeY ("", Float) = 2

    _Speed ("播放速度", Float) = 150

 }

 SubShader {

  // 这里使用Unity3d自带光照模型Lambert

  // 不用做顶点处理,只需要一个表面处理函数surf

  CGPROGRAM

  #pragma surface surf Lambert alpha

 

  // 声明参数

  fixed4 _Color;

  sampler2D _MainTex;

  uniform fixed _SizeX;

  uniform fixed _SizeY;

  uniform fixed _Speed;

  // 获取_MainTexUV信息定义输入结构体

  struct Input {

     // 在贴图变量前加上uv表示提取uv(二维坐标)

     float2 uv_MainTex;

  };

  void surf (Input IN, inout SurfaceOutput o) {

     // 获取单元格UV

     float2 cellUV = float2(IN.uv_MainTex.x /_SizeX, IN.uv_MainTex.y /_SizeY);

     // UV坐标值范围为0-1,获取单元格宽度

     float deltaX = 1 / _SizeX; // 单元格增量宽度

     float deltaY = 1 / _SizeY; // 单元格增量高度

  

     // 当前播放总索引

     int index = _Time * _Speed;

     // 求列索引

     int col = fmod(index, _SizeX);

     // 求行索引

     int row = index / _SizeX;

     // 原始UV + 当前格增量

     cellUV.x += col * deltaX;

     cellUV.y += row * deltaY;

     // 创建tex2d(材质,uv)*主色

     fixed4 c = tex2D(_MainTex, cellUV) * _Color;

     // RGB

     o.Albedo = c.rgb;

     // 透明度

     o.Alpha = c.a;

  }

  ENDCG

 }

 

步骤:

1.unity里新建一个shader,使用上面代码。

 

2.准备一张序列帧贴图。

 

3.unity里新建一个material,给其指定上面新建的shader,并设置序列帧贴图。设置行列,上面贴图19列。

 

4.在场景中新建一个plane,将上面的material拖至上面即可。

 

5.运行展示

一个走动的man

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

标签: