Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to move vertices into relative direction

Discussion in 'Shaders' started by Buttermilch, Oct 8, 2023.

  1. Buttermilch

    Buttermilch

    Joined:
    Nov 23, 2016
    Posts:
    31
    I'm basically trying to make a neat collision effect.
    When the player vehicle hits my mesh, I want to make the vertices fly away from the player into the direction they hit the mesh.

    My current approach is sending over the transform.forward of the player when the collision happens.
    Then I convert this vector into world space and apply it to the vertex with the absolute normal vector before transforming into clip space.
    (making the normal absolute results in all vertices flying into the same general direction)

    It works almost but it does not seem to take the mesh orientation into account and thus the vertices are not flying into the correct direction. Hope someone can help me out.


     
    v2f vert (appdata v)
    {
    v2f o;
    //_VertexDirection = transform.forward when collision occours
    float3 explosionDir = _VertexDirection;
    float3 explosionPoint = v.vertex - explosionDir;
    float3 explosionForce = explosionPoint - v.vertex;
    explosionForce = mul(unity_ObjectToWorld, explosionForce);

    float3 dir = abs(v.normal) * -explosionForce ;
    v.vertex.xyz += dir * _VertexOffset ;

    o.vertex = UnityObjectToClipPos(v.vertex);
    o.worldNormal = UnityObjectToWorldNormal(v.normal);
    o.screenPosition = ComputeScreenPos(o.vertex);
    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    o.worldPosition = mul(unity_ObjectToWorld, v.vertex);
    return o;
    }
     
  2. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,495
    When the vehicle hits, convert the direction into local space direction for the vehicle before setting it on the material. This way no matter if the vehicle continues to rotate, the vertices will still displace in the same relative direction.

    v.vertex is in object (local space) by default, so that will play nice with the direction offset.

    Not sure why you're using the vertex normal here if you're already feeding a direction into the shader.

    If you feed the local space direction in (with magnitude intact), then it's only 1 line needed,
    v.vertex.xyz += _VertexDirection
    .

    Modulate the magnitude of the direction vector from C# if you're trying to do some wobble.