unity urp 10 RenderTexture
一、思路render texture的过程很简单,就是在创建一个render texture,然后设置某个相机,将该相机观察到的图像输出到这个texture中。之后就可以将这个render texture作为纹理来使用了。过程如下所示。
二、代码
这里使用render texture实现一种镜子的效果,即创建一个相机从镜子的方向观察,然后将图像输出到render texture中,之后再shader中将render texure的uv坐标水平反转即可(1-uv.x)。
Shader "Unlit/12_Mirror"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
HLSLINCLUDE
#include"Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include"Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
struct Attributes
{
float3 positionOS: POSITION;
half3 normalOS: NORMAL;
half4 tangentOS: TANGENT;
float2 texcoord: TEXCOORD0;
};
struct Varyings
{
float2 uv: TEXCOORD0;
float3 positionWS: TEXCOORD1;
half3 normalWS: TEXCOORD2;
half3 tangentWS: TEXCOORD3;
half3 bitangentWS: TEXCOORD4;
float4 positionCS: SV_POSITION;
};
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
CBUFFER_END
sampler2D _MainTex;
ENDHLSL
Pass
{
Tags
{
"LightMode"="UniversalForward"
}
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
Varyings vert (Attributes input)
{
Varyings output;
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS);
VertexNormalInputs vertexNormalInputs = GetVertexNormalInputs(input.normalOS, input.tangentOS);
output.positionCS = vertexInput.positionCS;
output.positionWS = vertexInput.positionWS;
output.normalWS = vertexNormalInputs.normalWS;
output.tangentWS = vertexNormalInputs.tangentWS;
output.bitangentWS = vertexNormalInputs.bitangentWS;
output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
//水平翻转
output.uv.x = 1-output.uv.x;
return output;
}
half4 frag (Varyings input) : SV_Target
{
Light mainLight = GetMainLight();
float3 lightDirWS = mainLight.direction;
float3 normalWS = normalize(input.normalWS);
float3 viewDirWS = SafeNormalize(GetCameraPositionWS()-input.positionWS);
float3 reflectWS = reflect(-viewDirWS,normalWS);
half4 col = tex2D(_MainTex, input.uv);
return col;
}
ENDHLSL
}
}
}
三、结果
页:
[1]