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 deform mesh and mesh collider with another collider

Discussion in 'Scripting' started by kader1081, Aug 14, 2023.

  1. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    365
    Hi, I am trying to make an trench there is a ground which has mesh and mesh collider i want to make an dent which is same size with trench trench will have box collider. i did with terrain but i couldn't make with mesh. I was thinking i can make a dent with collision points. I am having problem with setting triangles
     
    Last edited: Aug 14, 2023
  2. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Mesh manipulation is very complicated. As you would need to recreate an array of all the verts, triangles, and UVs, then modify the verts where you want them, and then reapply the mesh.

    This an example of just 5 vertices:
    Code (CSharp):
    1. void Start()
    2. {
    3.     mesh = new Mesh();
    4.     GetComponent<MeshFilter>().mesh = mesh;
    5.  
    6.     CreateMesh();
    7.     UpdateMesh();
    8. }
    9.  
    10. void CreateMesh()
    11. {
    12.     verts = new Vector3[5];
    13.     verts[0] = leftBottom;
    14.     verts[1] = leftTop;
    15.     verts[2] = center;
    16.     verts[3] = rightTop;
    17.     verts[4] = rightBottom;
    18.  
    19.     tris = new int[12];
    20.     tris[0] = 0;
    21.     tris[1] = 1;
    22.     tris[2] = 2;
    23.     tris[3] = 1;
    24.     tris[4] = 3;
    25.     tris[5] = 2;
    26.     tris[6] = 3;
    27.     tris[7] = 4;
    28.     tris[8] = 2;
    29.     tris[9] = 4;
    30.     tris[10] = 0;
    31.     tris[11] = 2;
    32.  
    33.     uvs = new Vector2[5];
    34.     uvs[0] = new Vector2(0, 0);
    35.     uvs[1] = new Vector2(0, 2);
    36.     uvs[2] = new Vector2(1, 1);
    37.     uvs[3] = new Vector2(2, 2);
    38.     uvs[4] = new Vector2(2, 0);
    39. }
    40.  
    41. public void UpdateMesh()
    42. {
    43.     mesh.Clear();
    44.  
    45.     mesh.vertices = verts;
    46.     mesh.triangles = tris;
    47.  
    48.     mesh.uv = uvs;
    49.     mesh.RecalculateNormals();
    50. }
     
  3. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    365
    I was afraid of that . I subdivided my plane to 1000 polygon. Instead of creating new vertices i modify vertices that inside of the box collider