Hello,
First time poster, pretty stumped right now as to how to do this because the way I’ve been told to do so does not work 100% of the times. Basically, I’m trying to create a random tree generator. This tree generator works, except that if I rotate the “Earth” (For now it’s only being rotated on the X axis), the trees still spawn with a Y coordinate of:
treePrefab.transform.localScale.y/2
(Above code works fine)
But if I take the “Earth”, and rotate it 45 degrees, obviously that would not work, as some trees would be underground essentially. So what I was doing was looking at what I knew and I know the X coordinate of the treePrefab, I know the Angle of the “Earth” piece, and I know that
tan(angle) = opp/adj
And that the Opposite is what the Y coordinate of the tree (Plus the treePrefabs y/2), then the value I need would be solved with the following equation
int yPos = Mathf.tan(angleInRadians) * xCoordinate
However int yPos
is not what it should be. Help?
EDIT:
This is my complete, current code (as of posting this, no edits since)
using UnityEngine;
using System.Collections;
public class TreeGenerator : MonoBehaviour {
public GameObject terrainPiece;
public GameObject treePrefab;
public int spread = 10;
// Use this for initialization
void Start ()
{
foreach (Transform child in terrainPiece.transform)
{
float x = child.transform.localScale.x;
float z = child.transform.localScale.z;
float rX = child.transform.localEulerAngles.x;
//float rZ = child.transform.localRotation.z;
float tanX = Mathf.Tan(rX * Mathf.Deg2Rad);
//child.transform.localScale.y/2 + treePrefab.transform.localScale.y/2
for (int i = 1; i <= (x/spread); i++)
{
float posX = Random.Range(0, x) - (x/2);
float posZ = Random.Range(0, z) - (z/2);
float newX = tanX * posX;
//print (newX);
Instantiate (treePrefab, child.transform.position + new Vector3 (posX, newX, posZ), Quaternion.identity);
}
}
}
// Update is called once per frame
void Update ()
{
}
}