URP-利用矩阵在Shader中实现物体的平移和缩放

一、平移

方法一:

v.positionOS.xyz += _Translate.xyz;

方法二:

利用矩阵实现平移:

二、缩放

方法一:

v.positionOS.xyz *= _Scale.xyz*_Scale.w; _Scale.w实现全局缩放

方法二:

复制代码
Shader"unity/Translation"
{
	Properties
	{
		_Color("Color",Color)=(0,0,0,0)
		_Translate("Translate",Vector)=(0,0,0,0)
		_Scale("Scale",Vector)=(1,1,1,1)
	 }

	SubShader
	{
		Tags
		{
			"RenderPipeline" = "UniversalPipeline"
		 }
		Pass
		{
			HLSLPROGRAM

			#pragma vertex vert
			#pragma fragment frag

			#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
			#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl"

			CBUFFER_START(UnityPerMaterial)
			float4 _Color;
			float4 _Translate;
			float4 _Scale;
			CBUFFER_END

			struct Attributes
			{
				float4 positionOS : POSITION;
			 };

			struct Varyings
			{
				float4 positionCS : SV_POSITION;
			 };

			Varyings vert(Attributes v)
			{
				Varyings o = (Varyings)0;

				//平移
				// v.positionOS.xyz += _Translate.xyz;
				//平移矩阵
				float4x4 T = float4x4(
				 1,0,0,_Translate.x,
				 0,1,0,_Translate.y,
				 0,0,1,_Translate.z,
				 0,0,0,1
				 );

				v.positionOS = mul(T,v.positionOS);

				//缩放:将向量的每个分量分别与对应的缩放因子相乘
				//(v.positionOS.x,v.positionOS.y,v.positionOS.z) * (_Scale.x,_Scale.y,_Scale.z)
				//=(v.positionOS.x*Scale.x,v.positionOS.y*_Scale.y,v.positionOS.z*_Scale.z)
				// v.positionOS.xyz *= _Scale.xyz*_Scale.w;  _Scale.w实现全局缩放

				//缩放矩阵
				float3x3 Scale = float3x3(
				 _Scale.x,0,0,
				 0,_Scale.y,0,
				 0,0,_Scale.z
				 );

				v.positionOS.xyz = mul(Scale,v.positionOS.xyz)*_Scale.w;

				o.positionCS = TransformObjectToHClip(v.positionOS);
				return o;
			 }

			float4 frag(Varyings i):SV_Target
			{
				return _Color;
			 }

			ENDHLSL
		 }
	 }
 }
相关推荐
星火撩猿39 分钟前
常见游戏引擎介绍与对比
unity·ue5·游戏引擎·godot
sky_smile_Allen2 小时前
[Unity]-[UI]-[Prefab] 关于Unity UGUI 的布局及组件讲解
ui·unity·游戏引擎
是阿根19 小时前
unity使用iTextSharp生成PDF文件
unity·c#·游戏引擎
岩中竹1 天前
力扣热题100题解(c++)—矩阵
数据结构·c++·程序人生·算法·leetcode·矩阵
byxdaz1 天前
矩阵运算和线性代数操作开源库
矩阵
常城1 天前
Unity中通过TMP使用图片字体
unity·游戏引擎
User_芊芊君子1 天前
【C语言经典算法实战】:从“移动距离”问题看矩阵坐标计算
c语言·算法·矩阵
惊鸿醉1 天前
⭐Unity 开发 | 如何通过 NTP 网络时间实现精准的跨平台时间同步【附完整源码 + UI 模块 + 偏差分析】
网络·unity·游戏引擎
weixin_428498491 天前
使用HYPRE库并行装配IJ稀疏矩阵
线性代数·矩阵