- Home /
Creating objects which are facing center of a sphere
I´m making a game with planets as terrain and I want to spawn random trees by script. With my script trees spawn randomly on the sphere but their all in one rotation.
I´ve tried a lot of ways to make the spawn like in this picture :
My script so far :`using UnityEngine; using System.Collections;
public class TreeSpawer : MonoBehaviour {
public float TreeNumber;
public GameObject tree;
public float PlanetRadius;
public GameObject PlanetOrigin;
void Start () {
for(int i=0; i<TreeNumber;i++) {
Vector3 origin = PlanetOrigin.gameObject.transform.position;
Vector3 onPlanet = Random.onUnitSphere * PlanetRadius;
Vector3 onYaxis = new Vector3(0,PlanetRadius,0);
var Rotation = Vector3.Angle(;
Instantiate(tree, onPlanet, "Rotation");
}
}
// Update is called once per frame
void Update () {
}
} ` Can you tell me how i get this done ? :) Thank you
TheSakuron
Answer by maccabbe · May 25, 2015 at 11:09 PM
A simple way to do this would be to use Transform.LookAt http://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Something like
transform.LookAt(PlanetOrigin.transform.position);
will cause the z vector of the trees to be towards the the center of a sphere
However depending on how you modeled the trees, the forward vector might be coming out of the top, the bottom, or a side. If all your trees will need to have their rotation adjusted by the same amount then use Quaternion*Quaternion to adjust the rotation, i.e. the following will adjust the rotation 90 degrees along the x axis
transform.rotation=transfrom.rotation*Quaternion.Euler(90, 0, 0);
So your code can look something like
public float TreeNumber;
public GameObject tree;
public float PlanetRadius;
public GameObject PlanetOrigin;
void Start () {
for(int i=0; i<TreeNumber;i++) {
Vector3 origin = PlanetOrigin.gameObject.transform.position;
Vector3 onPlanet = Random.onUnitSphere * PlanetRadius;
GameObject newGO=Instantiate(tree, onPlanet, Quaternion.identity) as GameObject;
newGO.LookAt(PlanetOrigin.transform.position);
newGO.transform.rotation=newGO.transform.rotation*Quaternion.Euler(90, 0, 0);
}
}
Thank you very much ! This is exactly what I was looking for :D
Your answer
Follow this Question
Related Questions
How to rotate object in instantiate with float value 1 Answer
Making a shotgun shooting 45 degrees to the left of the mouse 1 Answer
help with instantiating gameobject at random postition from a target gameobject? 1 Answer
orienting player in one direction 1 Answer
Instantiating a prefab and values 1 Answer