@mochi_53 (mo chi)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Unity 3D空間に配置したSpriteでのZ-Fightingについて

発生している問題

3D空間に配置したSpriteに影をつけるために下記サイトを参考にシェーダーを作成したのですが表示がちらついてZFightingが発生してしまいます。
ZTest Alwaysを追加で記入したところキャラクターの表示は正しくなりましたが手前にあるオブジェクトよりも前に描画されるようになり困っています。

解決したいこと

表示がちらつかず、手前のオブジェクトよりも前に描画されない状態にしたいのですが何かいい方法はないでしょうか?
検索キーワードだけでも十分ですので何か手掛かりをいただけると幸いです。

参考サイト : https://sleepygamersmemo.blogspot.com/2017/07/unity-sprites-shadow-2.html
使用キャラクターアセット : https://assetstore.unity.com/packages/2d/characters/cute-2d-girl-wizard-155796
Unityバージョン : 2021.3.14f1

スクリーンショット 2022-11-25 214141.png

Shader "Custom/Cutout Double-sided" {
	Properties {
		_Cutoff ("Cutoff", Range(0,1)) = 0.5
		_Color ("Color", Color) = (1,1,1,1)
		_MainTex ("Albedo (RGB)", 2D) = "white" {}
		_Glossiness ("Smoothness", Range(0,1)) = 0.5
		_Metallic ("Metallic", Range(0,1)) = 0.0
	}
	SubShader {
		Tags { "Queue"="AlphaTest" "RenderType"="TransparentCutout" }
		LOD 200
		
		Cull Off
		//ZTest Always
		
		CGPROGRAM
		#pragma surface surf Standard alphatest:_Cutoff addshadow fullforwardshadows
		#pragma target 3.0
 
		sampler2D _MainTex;
		
		struct Input {
			float2 uv_MainTex;
		};
		
		half _Glossiness;
		half _Metallic;
		fixed4 _Color;
 
		void surf (Input IN, inout SurfaceOutputStandard o) {
			fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
			o.Albedo = c.rgb;
			o.Metallic = _Metallic;
			o.Smoothness = _Glossiness;
			o.Alpha = c.a;
		}
		ENDCG
 
		// ここから追加
		Cull Front
		
		CGPROGRAM
 
		#pragma surface surf Standard alphatest:_Cutoff fullforwardshadows vertex:vert
		#pragma target 3.0
 
		sampler2D _MainTex;
 
		struct Input {
			float2 uv_MainTex;
		};
 
		// 法線を反転させて裏面の影の描写がきちんと行われるようにする
		void vert (inout appdata_full v) {
			v.normal.xyz = v.normal * -1;
		}
 
		half _Glossiness;
		half _Metallic;
		fixed4 _Color;
		
		void surf (Input IN, inout SurfaceOutputStandard o) {
			fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
			o.Albedo = c.rgb;
			o.Metallic = _Metallic;
			o.Smoothness = _Glossiness;
			o.Alpha = c.a;
		}
		ENDCG
	}
	FallBack "Diffuse"
}
0 likes

1Answer

他のシェーダだとどうなりますか?

正直シェーダは詳しくないのですが、おそらく2回レンダリングされるようになっていると思いますが、最初が「Cull Off」で後が「Cull Front」だと、裏面が2度レンダリングされてしまうので、z-fightingの原因になりかねないような気がします。
最初の「Cull Off」を「Cull Back」(もしかすると「Cull Front」?)にするといいのでは?と思います。

あと、一般的な話ですが、z-fightingは主にZバッファの精度が原因です。
カメラのNearClipとFarClipの差が大きいとZバッファの精度が粗くなり、それが原因でz-fightingが起きやすくなることがあります。
NearClipとFarClipはできる限り狭めるようにしたほうがいいです。

0Like

Your answer might help someone💌