Changing collider shape based on vertex shader

I am building a game and I have written a vertex shader that reshapes a cube based on the position on the x axis. Due to the deformation I want to also adjust the collider. In 2D I have done that by adjusting the polygon collider 2D, however I had no such luck In the 3D side of things (mesh collider). I have tried to insert similar code into he c# script of the cube, however I am not able to restore the original veritices in any way so they get distorted over time. Furthermore I haven’t been able to apply the mesh to the collider.

code:

```csharp
*Shader “Custom/Cube Deformation”
{
Properties
{
[NoScaleOffset] _MainTex(“Texture”, 2D) = “white” {}
}
SubShader
{
Pass
{
Tags{ “LightMode” = “ForwardBase” }

    CGPROGRAM

#pragma vertex vert
#pragma fragment frag
#include “UnityCG.cginc”
#include “UnityLightingCommon.cginc”

    struct v2f
{
    float2 uv : TEXCOORD0;
    fixed4 diff : COLOR0;
    float4 vertex : SV_POSITION;
};

v2f vert(appdata_base v)
{
    v2f o;
    float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
    o.vertex = UnityObjectToClipPos(v.vertex + (v.vertex * (sin(abs(worldPos.x / 2)) * 2) * 0.4f));
    o.uv = v.texcoord;
    half3 worldNormal = UnityObjectToWorldNormal(v.normal);
    half nl = max(0, dot(worldNormal, _WorldSpaceLightPos0.xyz));
    o.diff = nl * _LightColor0;

    // the only difference from previous shader:
    // in addition to the diffuse lighting from the main light,
    // add illumination from ambient or light probes
    // ShadeSH9 function from UnityCG.cginc evaluates it,
    // using world space normal
    o.diff.rgb += ShadeSH9(half4(worldNormal,1));
    return o;
}

sampler2D _MainTex;

fixed4 frag(v2f i) : SV_Target
{
    fixed4 col = tex2D(_MainTex, i.uv);
col *= i.diff;
return col;
}
    ENDCG
}
}

}*
* *csharp
*C#:
private void Start()
{
verts = GetComponent().mesh.vertices;
}

void Update () {
    Mesh mesh = GetComponent<MeshFilter>().mesh;
    Vector3[] vertices = verts;
    int i = 0;
    while (i < vertices.Length)
    {
        vertices += transform.position * 0.001f;
        i++;
    }
    mesh.vertices = vertices;
    mesh.RecalculateBounds();
    GetComponent<MeshCollider>().sharedMesh = null;
    GetComponent<MeshCollider>().sharedMesh = mesh;
}*

```
Can I somehow apply a vertex shader on a collider? Can I somehow transfer the vertecies from the shader to the collider?

As far as I have found no and no. You would have to do the vertex deformation on the CPU and then update the mesh collider, but that can be very very slow of complex meshes.

I won’t be using complex meshes (only one cube)

well then that should be find doing it all on the CPU and updating the mesh collider.

1 Like