Search code examples
unity-game-enginepositionmeshtriangle

Generating a mesh in Unity: How do I set triangle vertices to align with points from the next GameObject?


I want to generate a mesh in Unity. I have GameObjects (segments) that contain GameObjects (points).

To create a triange mesh, I set two of the three triangle vertices to the two points of the current GameObject. The third triangle vertice must then be set to a point from the next GameObject. However, the triangle vertice does not correctly lign up to the point of the next GameObject.

See screenshot (the blue lines show the expected result): Incorrect triangles

I have tried using InverseTransformPoint to calculate where the third vertice of the triangle should go. As you can see, it goes into the right direction but it does not totally align.

Here is the bit of interesting code:

foreach(Segment segment in segments)
{
    Mesh mesh = segment.gameObject.GetComponent<MeshFilter>();
    mesh.Clear();
                
    List<Vector3> vertList = new List<Vector3>();

    Vector3 relativeToLastSegment = lastSegment.yellowDotRight.transform.InverseTransformPoint(segment.transform.position);
    vertList.Add(relativeToLastSegment);     //  Right road end of last sector - DOES NOT ALIGN CORRECTLY

    vertList.Add(new Vector3(0f, 0f, -segment.yellowDotRightDistanceFromCenter * thicknessFactor));   //  Right road end of current sector
    vertList.Add(new Vector3(0f, 0f, segment.yellowDotLeftDistanceFromCenter * thicknessFactor));     //  Left road end of current sector

    //  Create verts
    mesh.vertices = vertList.ToArray();
    mesh.triangles = new int[] { 0, 1, 2 };
    meshf.mesh = mesh;

    lastSegment = segment;
}

Any ideas what I am missing?


Solution

  • Try this transformation

    // The right vertex from the last loop
    var lastRightLocal = new Vector3(0f, 0f,
                         -lastSegment.yellowDotRightDistanceFromCenter * thicknessFactor);
    
    // Transform it to the world space
    var lastRightWorld = lastSegment.transform.TransformPoint(lastRightLocal);
    
    // Transform the last right vertex from the world space
    // to the local space of the current mesh
    var currentLeftLocal = segment.transform.InverseTransformPoint(lastRightWorld);
    vertList.Add(currentLeftLocal);