Objects not spawning up-right.

Hey there!
I’m back with another interesting problem!

Haha, i’ve successfully got a “randomSurfaceSpawn” script working which
Spawns objects on the surface of a sphere and aligns them perfectly with the mesh’s collider.

What i need to do now is make there objects stand upright nomatter where they are instantiated.

My code so far:

Attached to sphere - spawns objects and attached them to the mesh collider

var prefab : GameObject;
var planet : GameObject;
var i = 0;
var tNum : int;

function Awake()
{
		tNum = Random.Range(100,700);
}


function Update()
{
	if(i < tNum)
	{
		i++;
		GetPointOnMesh();
		spawn();
	}
	else 
	{
		i = i;
	}
}


function GetPointOnMesh() : RaycastHit{
    var length : float = 1000.0;
    var direction : Vector3 = Random.onUnitSphere;
    var ray : Ray = Ray(transform.position + direction*length,-direction);
    var hit : RaycastHit;
    collider.Raycast (ray, hit, length*2);
	//prefab.transform.parent = hit.transform.parent;
	
    return hit;
}


function spawn() 
{
    	var randomPoint = GetPointOnMesh();
     	var spawnPreferences = Instantiate(prefab, randomPoint.point, Quaternion.identity);
    	spawnPreferences.transform.eulerAngles.y = Random.Range(0, 360);
}

(The purpose for the function Updates lengthy for loop is because it lays it out simpler for me, and has worked 100% of the time with speed and precision compared to the for(var : int = 0; i < tNum; i++) loop).

Rotation script - attached to Tree in order to rotate it upright

var target : Transform;
	
	function Update () 
	{
		var relativePos = target.position + transform.position;
		var rotation = Quaternion.LookRotation(relativePos);
		transform.rotation = rotation;
	}

My problem lies somewhere within my rotate tree script but i have no clue where!

Please help me on this one oh mighty unity guru’s!

Thank you for reading,
Sincerely,

Bakos

Make a couple of assumptions here:

  • You’ve constructed your trees so that when they have rotation (0,0,0), ‘y’ is facing Vector3.up.
  • target (which I don’t see you initialize), is the sphere.

You can do:

var dir = transform.position - target.position;
transform.rotation = Quaternion.FromToRotation(transform.up, dir) * transform.rotation;

Note if the trees are not going to be moving, you could do this in your spawn() function instead and not do it every frame on the tree:

var dir = spawnPreferences.transform.position - transform.position;
var q = Quaternion.FromToRotation(spawnPreferences.transform.up, dir);
spawnPreferences.transform.rotation = q * spawnPreferences.transform.rotation;