Article directory
Preface
Screen coordinates of Shader in Unity
1. Screen coordinates
1. Coordinates of screen pixels
2. Screen coordinate normalization
Use the formula: Screen normalized coordinates = current pixels/total pixels
2. Get the current screen pixels and total pixels in Unity
1. Get the total pixels of the screen, use the _ScreenParams parameter
_ScreenParams
Screen related parameters, unit is pixels.
x represents the width of the screen
y represents the height of the screen
z represents 1+1/screen width
w represents 1+1/screen height
2. Get the pixels on the current fragment
UNITY_VPOS_TYPE screenPos: VPOS
1. The position of the current fragment on the screen (unit is pixel, can be divided by _ScreenParams.xy for normalization), this function only supports #pragma target 3.0 and above compilation instructions 2. Under most
platforms VPOS returns a four-dimensional vector, and some platforms are two-dimensional vectors, so UNITY_VPOS_TYPE needs to be used to distinguish them uniformly. 3.
When using VPOS, you cannot define SV_POSITION in v2f, which will conflict, so you need to change the input of the vertex shader placed in the parameters of (), and SV_POSITION is added out.
How to use: Used when passing in parameters to the fragment shader
fixed4 frag (v2f i,UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
{
}
Because the type of VPOS is not uniform on different platforms, some are float2 and some are float4, so we use the type UNITY_VPOS_TYPE provided by Unity and let Unity handle it automatically.
When using UNITY_VPOS_TYPE screenPos: VPOS as the input of the fragment shader, the input of the vertex shader needs to be modified.
Modified code:
Shader "MyShader/P0_10_3"
{
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f
{
float2 uv : TEXCOORD0;
};
//在顶点着色器的输入处,不用appdata,直接使用用到的参数,防止 SV_POSITION 重复定义
v2f vert (
float4 vertex : POSITION,
out float4 pos : SV_POSITION
)
{
v2f o;
pos = UnityObjectToClipPos(vertex);
return o;
}
fixed4 frag (v2f i,UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
{
float2 screenUV = screenPos.xy / _ScreenParams.xy;
return fixed4(screenUV,0,0);
}
ENDCG
}
}
}
Effect:
Output the effect of screen normalized x: return screenUV.x;
Output the effect of screen normalization y: return screenUV.y;