Как динамически создавать сетку в unity

#c# #unity3d #dynamic #mesh

#c# #unity-игровой движок #динамический #сетка

Вопрос:

У меня есть вершины, которые имеют значение цвета.

Я хотел бы создать сетку, используя vertex с теми же значениями цвета.

введите описание изображения здесь

Эта картинка является примером.

Я сделал снимки с помощью своего телефона Android и произвел сегментацию изображения объекта

Итак, я получил значение цвета, соответствующее значению координаты.

Мне удалось просто создать текстуры. пожалуйста, проверьте изображение. введите описание изображения здесь

Но мне нужен сетчатый объект.

Ниже приведен код создания текстуры.

 var pixel = await this.segmentation.SegmentAsync(rotated, scaled.width, scaled.height);
// int pixel[][];                   // image segmentation using tensorflow

Color transparentColor = new Color32(255, 255, 255, 0);  // transparent
for (int y = 0; y < texture.height; y  )
{
      for (int x = 0; x < texture.width; x  )
      {
             int class_output = pixel[y][x];   

              texture.SetPixel(x, y, pixel[y][x] == 0 ? transparentColor : colors[class_output]);
      }
}
texture.Apply();
  

Как я могу создать объект сетки?

Комментарии:

1. С помощью класса Unity3D Mesh … docs.unity3d.com/ScriptReference/Mesh.html

2. если у вас есть контур, процесс, который вы ищете, называется триангуляцией (если 2d подходит)

3. Очевидно, вы используете ARCore. Вы можете использовать извлеченные точки для создания своих сеток, как упоминал @Dave. Однако я сильно сомневаюсь, что вы получите правильную сетку в конце этой процедуры.

Ответ №1:

1- Установите сборный файл с помощью MeshFilter и MeshRenderer.

2- Переменные внутри скрипта, которые вам нужно будет заполнить.

 // This first list contains every vertex of the mesh that we are going to render
public List<Vector3> newVertices = new List<Vector3>();

// The triangles tell Unity how to build each section of the mesh joining
// the vertices
public List<int> newTriangles = new List<int>();

// The UV list is unimportant right now but it tells Unity how the texture is
// aligned on each polygon
public List<Vector2> newUV = new List<Vector2>();


// A mesh is made up of the vertices, triangles and UVs we are going to define,
// after we make them up we'll save them as this mesh
private Mesh mesh;
  

3. Инициализируйте сетку

 void Start () {

  mesh = GetComponent<MeshFilter> ().mesh;

  float x = transform.position.x;
  float y = transform.position.y;
  float z = transform.position.z;

  newVertices.Add( new Vector3 (x  , y  , z ));
  newVertices.Add( new Vector3 (x   1 , y  , z ));
  newVertices.Add( new Vector3 (x   1 , y-1 , z ));
  newVertices.Add( new Vector3 (x  , y-1 , z ));

  newTriangles.Add(0);
  newTriangles.Add(1);
  newTriangles.Add(3);
  newTriangles.Add(1);
  newTriangles.Add(2);
  newTriangles.Add(3);

  newUV.Add(new Vector2 (tUnit * tStone.x, tUnit * tStone.y   tUnit));
  newUV.Add(new Vector2 (tUnit * tStone.x   tUnit, tUnit * tStone.y   tUnit));
  newUV.Add(new Vector2 (tUnit * tStone.x   tUnit, tUnit * tStone.y));
  newUV.Add(new Vector2 (tUnit * tStone.x, tUnit * tStone.y));

  mesh.Clear ();
  mesh.vertices = newVertices.ToArray();
  mesh.triangles = newTriangles.ToArray();
  mesh.uv = newUV.ToArray(); // add this line to the code here
  mesh.Optimize ();
  mesh.RecalculateNormals ();
 }
  

Этот код нарисует квадрат в месте сборки, если вы продолжите добавлять вершины, вы сможете сгенерировать более сложную сетку.

Источником информации является руководство по созданию mesh для ландшафта, подобного minecrat, проверьте ссылку для получения дополнительной информации.

Ответ №2:

Ответ, который был выбран наилучшим образом, на мой взгляд, ошибочен по четырем причинам. Во-первых, он устарел. Во-вторых, это сложнее, чем необходимо. В-третьих, это дает мало объяснений, и, наконец, в основном это просто копия из чужого поста в блоге. По этой причине я предлагаю новое предложение. Для получения дополнительной информации просмотрите документацию здесь.

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class meshmaker : MonoBehaviour {

    Mesh mesh;
    MeshFilter meshFilter;
    Vector3[] newVertices;
    int[] newTriangles;

    // Use this for initialization
    void Start () {
        //First, we create an array of vector3's. Each vector3 will 
        //represent one vertex in our mesh. Our shape will be a half 
        //cube (probably the simplest 3D shape we can make.

        newVertices = new Vector3[4];

        newVertices [0] = new Vector3 (0, 0, 0);
        newVertices [1] = new Vector3 (1, 0, 0);
        newVertices [2] = new Vector3 (0, 1, 0);
        newVertices [3] = new Vector3 (0, 0, 1);

        //Next, we create an array of integers which will represent 
        //triangles. Triangles are built by taking integers in groups of 
        //three, with each integer representing a vertex from our array of 
        //vertices. Note that the integers are in a certain order. The order 
        //of integers determines the normal of the triangle. In this case, 
        //connecting 021 faces the triangle out, while 012 faces the 
        //triangle in.

        newTriangles = new int[12];

        newTriangles[0] = 0;
        newTriangles[1] = 2;
        newTriangles[2] = 1;

        newTriangles[3] = 0;
        newTriangles[4] = 1;
        newTriangles[5] = 3;

        newTriangles[6] = 0;
        newTriangles[7] = 3;
        newTriangles[8] = 2;

        newTriangles[9] = 1;
        newTriangles[10] = 2;
        newTriangles[11] = 3;


        //We instantiate our mesh object and attach it to our mesh filter
        mesh = new Mesh ();
        meshFilter = gameObject.GetComponent<MeshFilter> ();
        meshFilter.mesh = mesh;


        //We assign our vertices and triangles to the mesh.
        mesh.vertices = newVertices;
        mesh.triangles = newTriangles;

}
  

Та да! Ваш собственный полукуб.

Комментарии:

1. Как насчет того, что другой ответ устарел? Насколько я могу судить, они в основном используют тот же метод, что и вы, но с несколькими дополнительными вызовами метода…

2. Могу ли я быть честным здесь? Я редко бываю на этом сайте, и я ответил на этот вопрос достаточно давно, что даже не помню, как отвечал на него. Возможно, я ошибаюсь, говоря, что она устарела. Я, вероятно, не сказал бы этого, если бы у меня не было причины. Был ли их ответ отредактирован с тех пор? Извините, я не могу больше помочь.

3. Честно — это всегда хорошо. Никаких правок нет, но кто знает, изменился ли выбранный ответ. Просто хотел убедиться, что я ничего не пропустил.