Unity3d 如何在Unity着色器中为VR获取正确的屏幕坐标?
我很难获得正确的屏幕坐标,所以我制作了这个小MWE来复制我在主要项目中看到的行为。我在Unity 3D中使用单次渲染和Windows混合现实耳机。我有一个着色器,它被设置为一个新材质“ppMaterial”,然后在Unity3d 如何在Unity着色器中为VR获取正确的屏幕坐标?,unity3d,shader,virtual-reality,windows-mixed-reality,Unity3d,Shader,Virtual Reality,Windows Mixed Reality,我很难获得正确的屏幕坐标,所以我制作了这个小MWE来复制我在主要项目中看到的行为。我在Unity 3D中使用单次渲染和Windows混合现实耳机。我有一个着色器,它被设置为一个新材质“ppMaterial”,然后在 void OnRenderImage(RenderTexture source, RenderTexture destination) { Graphics.Blit(source, destination, ppMaterial); } 在这个MWE中,着色器只需在屏幕边
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Graphics.Blit(source, destination, ppMaterial);
}
在这个MWE中,着色器只需在屏幕边缘绘制圆,因此我制作了一个简单的着色器:
Shader "Custom/ScreenShader" {
Properties {
}
SubShader {
Pass {
CGPROGRAM
#pragma fragment frag
#pragma vertex vert
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
half4 _MainTex_ST;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
float4 screenPos : TEXCOORD1;
};
float getDist(float2 isIn, float2 pos2){
return sqrt((isIn.x - pos2.x)*(isIn.x - pos2.x) + (isIn.y - pos2.y)*(isIn.y - pos2.y));
}
float4 NearBoundary(float2 isIn, v2f i)
{
float2 pos2 = float2(0.5,0.5);
float2 pos3 = float2(0,0.5);
float2 pos4 = float2(0.5,0.0);
float dist2 = getDist(isIn, pos2);
float dist3 = getDist(isIn, pos3);
float dist4 = getDist(isIn, pos4);
if(dist2<0.1){
return float4(0,0.5,0.5,1);
}
if(dist3.x<0.3){
return float4(0.5,0,0.5,1);
}
if(dist4.x<0.3){
return float4(0.5,0,0.5,1);
}
return tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv, _MainTex_ST));
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.screenPos = ComputeScreenPos(o.vertex);
o.uv = v.uv;
return o;
}
half4 frag(v2f i) : SV_Target {
float2 screenPos = i.screenPos;
return NearBoundary(screenPos, i);
}
ENDCG
}
}
}
Shader“自定义/屏幕着色器”{
性质{
}
子阴影{
通过{
CGP程序
#布拉格碎片碎片
#pragma顶点顶点
#包括“UnityCG.cginc”
均匀取样器2D_MainTex;
缅特克斯街4号;
结构appdata
{
浮动4顶点:位置;
float2uv:TEXCOORD0;
};
结构v2f
{
浮动4顶点:SV_位置;
float2uv:TEXCOORD0;
浮动4屏幕位置:TEXCOORD1;
};
浮点getDist(浮点2输入,浮点2位置2){
返回sqrt((isIn.x-pos2.x)*(isIn.x-pos2.x)+(isIn.y-pos2.y)*(isIn.y-pos2.y));
}
浮动4近边界(浮动2 isIn,v2f i)
{
float2 pos2=float2(0.5,0.5);
float2 pos3=float2(0,0.5);
float2 pos4=float2(0.5,0.0);
float dist2=getDist(isIn,pos2);
float dist3=getDist(isIn,pos3);
float dist4=getDist(isIn,pos4);
如果(dist2证明问题在于给出坐标的摄像机设置了targettexture,这似乎会弄乱坐标。然后,屏幕位置必须由
screenPos.x -= unity_StereoEyeIndex * 0.5;
screenPos.x *= 2;
还有,插入
RenderTextureDescriptor d = XRSettings.eyeTextureDesc;
d.width = d.width / 2; // THIS DOES NOT MAKE SENSE
RenderTexture t = new RenderTexture(d);
在C#-代码和设置中
uv.y = 1-uv.y
在着色器中,我终于摆脱了所有问题
为其他有这些超级奇怪问题的人发布这个