Hello everyone,
I am working on a marching cube terrain, my terrain is composed of chunks, each having it’s on mesh. I would like to assign a specific texture whenever the player dig into it but only in the diged part. The new texture should remain even if the player dig somewhere else even in the same chunk. So far what I tried :
1)Mesh vertex position comparaison idea : Register all the vertex position in a Vector3 array and everytime the player dig, it will compare all the new vertex position to the initial Vector3 array to see if it’s inside. If it’s inside I assign a new color to the vertex that will get read by a shader graph to apply my texture. problem: color is properly assigned but computing time is too high due to the GPU comparing several thousand vertex position everytime I dig a chunk.
2)Custom Shader idea : assign a color white to all vertex of my initial mesh at the creation then if my player dig the custom shader will change the vertex color to black if it’s in the range of the digged vertex. problem : If the player dig more than once in the same chunk, the previous black color will go back to white. I tried to set up a if statement but didn’t change much
Do you see any way to improve either of those ideas ? Or any other idea that might work in this case ?
Thank you !!
Here is the custom shader script in case it’s useful
Shader"Custom/TestShader"
{
Properties
{
_PlayerPos ("Player Position", Vector) = (0,0,0,0)
_Dist ("Distance Threshold", Float) = 10.0
}
SubShader
{
Tags { "RenderType"="Opaque" }
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float4 color : COLOR;
};
struct v2f
{
float4 pos : SV_POSITION;
float4 color : COLOR;
};
float4 _PlayerPos;
float _Dist;
bool _blue;
v2f vert(appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.color = v.color;
// calculate the distance between player and vertex
float distanceToPlayer = distance(_PlayerPos.xyz, mul(unity_ObjectToWorld, v.vertex).xyz);
// If distance is less than threshold, change color to black
if (v.color.r == 1)
{
if (distanceToPlayer < _Dist)
{
o.color = float4(0, 0, 0, 0); // black
v.color = float4(0, 0, 0, 0); // Update vertex color to black
}
}
return o;
}
fixed4 frag(v2f i) : SV_Target
{
return i.color;
}
ENDCG
}
}
}