- Home /
Orientate Planes created on vertices towards mehs they're spawned on
Hi! I spawn small planes on a huge mesh by writing the following:
var maxAmount : int = 10;
var mesh : Mesh = GetComponent(MeshFilter).mesh;
var vertices = mesh.vertices;
for (var i = 0; i < maxAmount; i++)
{
var someNum = Random.Range (0, vertices.length);
var spawnPoint = transform.TransformPoint(vertices[someNum]);
plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
plane.transform.position = spawnPoint;
Thus i don't define any rotation for the these created planes, they clearly all face in the same direction. The mesh on which they're spawned on looks like a rock, the normals look in many different directions. How can i make the planes rotate at creation in a way towards the mehs that it looks like as they would lie on it?
Thanks in advance!
Answer by robertbu · Apr 23, 2014 at 02:04 AM
I assume you want the planes to face away from the 'rock' so that you can see the surface of the plane. Vertices do not define normals...the triangles do. From what you are doing, it would be better to process each triangle and place the plane on the center of the triangle with the normal of the plane aligned with the normal of the triangle. The Mesh.normals supply the normal for each triangle, though you will need to do a Transform.TransformDirection() on it.
If you pivot point is in the center of your 'rock', then your code with something like this may be good enough:
var dir = spawnPoint - transform.position;
plane.transform.rotation = Quaternion.FromToRotation(Vector3.up, dir);
Note if you are going to be creating a lot of these, then you may not want to use the built-in plane. It has far more triangles than is necessary. You can use the CreatePlane editor script from the Wiki to make a two triangle, horizontal plane, or you could use a Quad and change the code I've outline to align Vector3.back with 'dir'.
thank you very for your answer! you were right about the triangles. i could solve it by placing the plane on a vertice of a random triangle on the mesh and then rotate it away from it by the direction of the triangles normal. here's my code: var maxAmount : int = 10; var mesh : $$anonymous$$esh = GetComponent($$anonymous$$eshFilter).mesh; var vertices = mesh.vertices; var normals = mesh.normals; var triangles = mesh.triangles;
for (var i = 0; i < maxAmount; i++)
{
var someNum = Random.Range (0, triangles.length);
var vert = vertices[triangles[someNum]];
var spawnPoint = transform.TransformPoint(vert);
var plane = Instantiate (prefPlane, spawnPoint, Quaternion.identity);
var dir = normals[triangles[someNum]];
plane.transform.rotation = Quaternion.FromToRotation(Vector3.up, dir);
}
and thanks for the tipp with the built-in plane :) i created one with the suggested createplane editor script with only two triangles and use it as the prefab 'plane' to instantiate it.