- Home /
Randomize Sphere & Smooth Vertex ( like in blender)
I'm looking to take a sphere mesh and randomize the height as well as smooth the vertex just like i'm able to do in blender (only I want to do this in C# within unity)
In blender when I have a sphere selected and click randomize, I am able to see different height and depth added to the sphere and there are no holes or problems.
My code:
Mesh mesh = GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
float [][] verticesArray;// = new float [vertices.Length][3];
verticesArray = new float [vertices.Length][];
int vertexCount = mesh.vertexCount;
int j = 0;
while (j < vertices.Length)
{
verticesArray[j] = new float [3];
Vector3 vUp = Vector3.MoveTowards(vertices[j],Vector3.zero, .05f);
vertices[j] = vUp * Random.Range(0.9f, 1.1f);
j++;
}
I'm trying to have the vertices move upwards (opposite of the direction towards the center) with some variation - but the sphere has a lot of gaps and is not smooth.
Please help !
Here is what is happening in Unity....
Here is what I'm trying to do in unity (the picture is while using blender)
How do you mean "smooth"? Your desired result looks faceted - anything but smooth to me! Have you tried the procedural examples of mesh deformation?
Sorry for the confusion - i posted a picture of the result in unity. There are gaps in the sphere.
Answer by maccabbe · Mar 02, 2015 at 12:57 AM
It seems like you have multiple vertices in certain locations which is why the mesh appears to be tearing.
You can either
Group together vertices that are in the same location and set all their new locations to the same position.
Use perlin noise to generate the same value for vertices in the same location. It I had to take a guess, blender probably uses perlin noise for the picture you provided.
Have only one vertex per position. However this would make flat shading difficult since vertices would be on multiple faces and can only have one normal.
Thanks for your input. Can you show via code how I could group vertices or achieve this ?
void Randomize(Vector3[] verts){
Dictionary<Vector3, List<int> > dictionary=new Dictionary<Vector3, List<int> >();
for(int x=0; x<verts.Length; x++){
if(!dictionary.Contains$$anonymous$$ey(verts[x])) {
dictionary.Add(verts[x], new List<int>());
}
dictionary[verts[x]].Add(x);
}
foreach($$anonymous$$eyValuePair<Vector3, List<int>> pair in dictionary) {
Vector3 newPos = pair.$$anonymous$$ey*Random.Range(0.9f, 1.1f);
foreach(int i in pair.Value) {
verts[i]=newPos;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613184640im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problems with importing Blender object 1 Answer
Object from blender having it's mesh changed when importing to unity 1 Answer
Blender Mesh rotation 3 Answers
Exporting files from blender to unity 2 Answers