- Home /
calculate position and rotation relatively to shpere (Planet)
Hi, Im trying come up with how spawn objects in random position (trees, stones) with right rotation relativly planet (sphere). Can anyone help me ? 
@albor2004 - psst, if Captain Pineapple's answer got you unblocked on this, it's polite to 'Accept' the answer.
Answer by Captain_Pineapple · Sep 03, 2021 at 12:42 PM
Hey there and welcome to the forum.
rotation can be solved like this assuming that the z-Axis is the axis along your trees:
tree.rotation = Quaternion.LookRotation(tree.position - sphere.position);
If the z-Axis is not the upward axis in your tree then the calculation is a bit more complex.
var tmpVec = tree.position - sphere.position;
tree.rotation = Quaternion.LookRotation(Vector3.Cross(Random.onUnitSphere ,tmpVec), tmpVec)
Important!: Due to the nature of a Vector cross product the latter calculation will fail if the random vector is exactly +- tmpVec. Keep this in mind and add a check for this if you use this solution.
As for the position. Depends. Do you want to add trees randomly? do you want a grid? there is no "correct" solution. Add more info on how you want to place trees.
In general you just have to normalize the vector and mutliply it by the spheres radius to get a vector that points exactly to the surface of your planet.
Thx for answer, I will try it. Yes, I want spawn trees randomly on sphere or in random area.
Answer by elenzil · Sep 03, 2021 at 06:34 PM
@captain_pineapple 's answer is excellent.
re positioning items randomly on a sphere, something like this is simple and robust, and has an expected runtime of about 2N. to get down to N is a little more involved.
// array of transforms to put in position.
// assuming these are children of the planet's transform,
// and that the planet's transform is rooted at the center of the planet.
Transform[] trees;
foreach (Transform t in trees) {
t.LocalPosition = Random.onUnitySphere * planetRadius;
t.LocalRotation = Quaternion.LookRotation(t.LocalPosition);
}
Your answer