Instantiating object aligned with mesh normal?

Hi, I’ve been batting my head against this for a bit so thought I’d ask here: I am instantiating objects on random points on a mesh, and want them to be aligned to the normals of those points, I’ve been through several forum threads and think I have done what’s needed re converting normals to rotations via Quaternion.Euler and so on but it still isn’t working. What am I missing?

public class InstOnMesh : MonoBehaviour {
    public GameObject leg;
    private GameObject[] legs;
    private Vector3[] vertices;
    private Vector3[] normals;
    private Quaternion[] rotations;

    private int thisLeg = 0;

    private System.Random random;
void Start ()
    {
        Mesh mesh = gameObject.GetComponent<MeshFilter> ().mesh;
        normals = mesh.normals;
        vertices = mesh.vertices;
        random = new System.Random ();
        legs = new GameObject[10];
        rotations = new Quaternion[vertices.Length];

        for (int i = 0; i < vertices.Length; i++) {
            rotations [i] = Quaternion.Euler (normals [i]);

            if (random.NextDouble () < 0.2f && thisLeg < 10) {
                Vector3 spawnPoint = transform.TransformPoint (vertices [i]);
                legs [thisLeg] = Instantiate (leg, spawnPoint, rotations [i]);
                legs [thisLeg].transform.SetParent (gameObject.transform, false);
                thisLeg++;
            }
        }
    }
}
1 Like

I know might be a bit offtopic but maybe its a way to make it work faster, i use Houdini FX to do this.
You can easy setup in houdini to place all objects to the ground using a mesh an so on.
Works so fine and its instancing like you want.

3253565--250596--upload_2017-10-14_15-14-27.png

1 Like

Thanks for the tip, I don’t think it would work in my case, but it’s good to know about it! Im doing this for an evolutionary algoritm sort of thingy - spawning creatures with a random amount of limbs and see how far they get in a terrain. It’s pretty basic atm, just a sphere with some moving cylinders on random mesh points, but they all get instantiated with their default rotation…

Nevermind, I need to use Quaternion.LookRotation instead of Quaternion.Euler . I really don’t get this quaternion business but I guess I’ll get used to it.