这篇文章主要为大家详细介绍了Unity实现旋转扭曲图像特效,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
旋转扭曲特效是指在一个圆形区域内扭曲所渲染的图像,其他像素的旋转程度随着距离的变化而变化。具体可以通过修改Shader来实现。
原始图片
扭曲图片
/*====================================================
屏幕扭曲特效Shader
======================================================*/
Shader "Hidden/TwirlEffects"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform float4 _MainTex_TexelSize;
half4 _MainTex_ST;
//旋转扭曲的中心
uniform float4 _CenterRadius;
//将旋转矩阵传入
uniform float4x4 _RotationMatrix;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
//将uv坐标变换到center坐标系中
o.uv = v.uv - _CenterRadius.xy;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float2 offest = i.uv;
//利用旋转矩阵旋转uv
float2 distortedOffset = MultiplyUV(_RotationMatrix,offest.xy);
//计算uv点在旋转圆中的位置
float2 tmp = offest / _CenterRadius.zw;
float t = min(1,length(tmp));
//根据uv点在圆中的位置插值uv移动的位置
offest =lerp(distortedOffset,offest,t);
//将uv坐标返回原坐标系中
offest += _CenterRadius.xy;
fixed4 col = tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(offest, _MainTex_ST));
return col;
}
ENDCG
}
}
}
此旋转特效主要就是对图像的uv值进行偏移,关键代码
float2 offest = i.uv;
//利用旋转矩阵旋转uv
float2 distortedOffset = MultiplyUV(_RotationMatrix,offest.xy);
//计算uv点在旋转圆中的位置
float2 tmp = offest / _CenterRadius.zw;
float t = min(1,length(tmp));
//根据uv点在圆中的位置插值uv移动的位置
offest =lerp(distortedOffset,offest,t);
//将uv坐标返回原坐标系中
offest += _CenterRadius.xy;
根据uv点的位置,对图像进行扭曲。
下面是脚本的源码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TwirlScripts : MonoBehaviour {
[ExecuteInEditMode]
public Vector2 radius = new Vector2(0.3f, 0.3f);
public Vector2 center = new Vector2(0.5f, 0.5f);
[Range(0.0f, 360.0f)]
public float angle = 0.0f;
public Material material;
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Matrix4x4 rotationMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one);
material.SetMatrix("_RotationMatrix", rotationMatrix);
material.SetVector("_CenterRadius", new Vector4(center.x, center.y, radius.x, radius.y));
Graphics.Blit(source, destination, material);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:Unity实现旋转扭曲图像特效
猜你喜欢
- c# 模拟线性回归的示例 2023-03-14
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- user32.dll 函数说明小结 2022-12-26
- 如何使用C# 捕获进程输出 2023-03-10
- Oracle中for循环的使用方法 2023-07-04
- Unity3D实现渐变颜色效果 2023-01-16
- Unity Shader实现模糊效果 2023-04-27
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- .NET CORE DI 依赖注入 2023-09-27