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
		 }
	 }
 }
相关推荐
Magnum Lehar7 小时前
3d游戏引擎的math矩阵实现
线性代数·矩阵·游戏引擎
HappyAcmen12 小时前
线代第二章矩阵第九、十节:初等变换、矩阵的标准形、阶梯形与行最简阶梯形、初等矩阵
笔记·学习·线性代数·矩阵
fancy16616612 小时前
搜索二维矩阵 II
c++·算法·矩阵
敲代码的 蜡笔小新13 小时前
【行为型之命令模式】游戏开发实战——Unity可撤销系统与高级输入管理的架构秘钥
unity·设计模式·架构·命令模式
人类发明了工具15 小时前
【优化算法】协方差矩阵自适应进化策略(Covariance Matrix Adaptation Evolution Strategy,CMA-ES)
线性代数·算法·矩阵·cma-es
驰愿1 天前
ET EntityRef EntityWeakRef 类分析
unity·et
程序员莫小特1 天前
【GESP真题解析】第 20 集 GESP 二级 2025 年 3 月编程题 1:等差矩阵
c语言·数据结构·c++·算法·青少年编程·矩阵
csdnzzt1 天前
CUDA编程——性能优化基本技巧
性能优化·矩阵·cuda
敲代码的 蜡笔小新1 天前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
敲代码的 蜡笔小新1 天前
【行为型之解释器模式】游戏开发实战——Unity动态公式解析与脚本系统的架构奥秘
unity·设计模式·游戏引擎·解释器模式