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
		 }
	 }
 }
相关推荐
寂寞的船1 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
探求虚无3 天前
用 AI 在 Unity 里做一款 RTS:最难的不是生成代码,而是证明它真的能玩
人工智能·unity·游戏引擎
17岁的勇气4 天前
Unity Shader unity文档学习笔记(二十二):shader变体
笔记·学习·unity
lisw054 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
DFT计算杂谈4 天前
可DIY布里渊区图像绘制编辑器
人工智能·机器学习·语言模型·矩阵·编辑器
Pniubi4 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
寂寞的船5 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
Pniubi5 天前
力扣73 矩阵置零
算法·leetcode·矩阵
kingx36 天前
Bugku 逆向 MatrixHunter:黑盒 oracle + GF(2) 消元出唯一解
网络安全·矩阵·逆向·ctf