- Home /
Lighting issues with script-generated polygons
I have several shapes made of four vertices each generated using code.
The shapes are correct, but their lighting comes out looking very strange.
Here's an example: https://imgur.com/a/Y3eUURG
I think it has something to do with normals, but I'm quite new to generating meshes. Any ideas?
This is the code I use to generate the map:
 public GameObject CreatePlaneFromPoints (Vector3[] points, Material material)
 {
     Vector3 center = centerFromPoints(points) * playerHeightScaleFactor;
     GameObject newObj = new GameObject();
     newObj.transform.position = center;
     MeshFilter mF = newObj.AddComponent<MeshFilter>();
     MeshRenderer mR = newObj.AddComponent<MeshRenderer>();
     mR.material = material;
 
     Mesh msh = new Mesh();
         
     msh.vertices = pointsRelativeTo(points, center);
         
     msh.triangles = new int[6] { 0, 1, 2, 2, 3, 0 };
         
     msh.RecalculateNormals();
 
     msh.uv = new Vector2[4]
     {
         new Vector2(0, 0), 
         new Vector2(0, 1), 
         new Vector2(1, 1), 
         new Vector2(1, 0)
     };
 
     mF.mesh = msh;
         
     // Collider
     newObj.AddComponent<MeshCollider>().sharedMesh = msh;
         
     return newObj;
 }
     
 private Vector3[] pointsRelativeTo(Vector3[] points, Vector3 relativeTo)
 {
     for (int i = 0; i < points.Length; i++)
     {
         points[i] = points[i] - relativeTo;
     }
 
     return points;
 }
     
 private Vector3 centerFromPoints(Vector3[] points)
 {
     int uC = -1000;
     Vector3 lowest = new Vector3(uC, uC, uC);
     Vector3 highest = new Vector3(uC, uC, uC);
     foreach (Vector3 p in points)
     {
         if (lowest.x == uC || p.x < lowest.x) lowest.x = p.x;
         if (lowest.y == uC || p.y < lowest.y) lowest.y = p.y;
         if (lowest.z == uC || p.z < lowest.z) lowest.z = p.z;
         if (highest.x == uC || p.x > highest.x) highest.x = p.x;
         if (highest.y == uC || p.y > highest.y) highest.y = p.y;
         if (highest.z == uC || p.z > highest.z) highest.z = p.z;
     }
 
     Vector3 diff = highest - lowest;
     return lowest + (diff / 2);
 }
Answer by WheresMommy · Dec 12, 2019 at 05:22 AM
This might help you: http://schemingdeveloper.com/2014/10/17/better-method-recalculate-normals-unity/ you have to make sure, that the normals are smoothed to their position in average on your surface generation. I guess, right now your normals are in tangent to their individual polygon.
Your answer
 
 
             Follow this Question
Related Questions
Procedural array of meshes problem / solved 1 Answer
Get all vertices in gameObject to array. 1 Answer
How do i modify a mesh Filter(C#)? 2 Answers
Multiple Cars not working 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                