Home > Software design >  How to Get Vertices World Coordinates With Correct Order in Unity?
How to Get Vertices World Coordinates With Correct Order in Unity?

Time:10-04

enter image description here

I have these vertices that represent borders of some provinces, I want their world coordinates in their correct order in Unity.

I Have tried:

    [SerializeField] private MeshFilter _mesh;
    [SerializeField] private LineRenderer _lineRenderer;

    [Serializable]
    public class Border
    {
        public Mesh borderMesh;
        public BorderProvince[] sharedBetween = new BorderProvince[2];
        public bool isACountryBorder;
    }

    [SerializeField] private List<Border> _borders;

    private List<Vector3> _drawnBorder = new List<Vector3>();

    [ContextMenu("Update Border Drawer")]
    private void UpdateBorderDrawer()
    {
        if (_borders.Count == 0 || _lineRenderer == null) return;

        _drawnBorder = new List<Vector3>();

        Matrix4x4 localToWorld = transform.localToWorldMatrix;

        foreach (Border border in _borders)
        {
            if (border.sharedBetween[0].ID != border.sharedBetween[1].ID)
            {
                border.isACountryBorder = true;
                for (int i = 0; i < border.borderMesh.vertices.Length; i  )
                {
                    _drawnBorder.Add(localToWorld.MultiplyPoint3x4(border.borderMesh.vertices[i]));
                }
            }
        }

        _lineRenderer.positionCount = _drawnBorder.Count;
        _lineRenderer.SetPositions(_drawnBorder.ToArray());
    }

It does work, it does give me vertices' world coordinates but they are not in order, when they are rendered by line renderer, they are rendered in a different order and they don't represent the border they should.

CodePudding user response:

Order of vertices in a mesh is not specified. What orders the vets is indices, you can read indices from a mesh, and use them as indexes to read the vertex list. This can however still not be in an order you expect, indices will only give you 'locally' ordered vests, forming segments or tris, there is nothing that would guarantee any particular order, as it doesn't matter for rendering. Looking at tris, you should be able to work out which is the next one, touching the current one, as they should share a vertex (but this is not guaranteed either, if not you'll need to work this out by comparing vertex positions).

  • Related