Reputation: 187
I'm proceduraly generating grass quads by raycasting onto a terrain surface, to make them seem more organic i'd like to add a random rotation on Z, but every one of my attempts rotates the grass block completely wildly.
without the random z rotation, the grass blocks are fine on the terrain but are aligned which doesn't feel very organic
void RaycastItem(ItemChunk itemChunk)
{
RaycastHit hit;
Vector3 randPosition = new Vector3(Random.Range(-gridSize/2, gridSize/2), -20, Random.Range(-gridSize/2, gridSize/2)) + itemChunk.coord;
if (Physics.Raycast(randPosition, Vector3.down, out hit, raycastDistance))
{
Quaternion spawnRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
Vector3 overlapTestBoxScale = new Vector3(overlapTestBoxSize, overlapTestBoxSize, overlapTestBoxSize);
Collider[] collidersInsideOverlapBox = new Collider[1];
int numberOfCollidersFound = Physics.OverlapBoxNonAlloc(hit.point, overlapTestBoxScale, collidersInsideOverlapBox, spawnRotation, spawnedObjectLayer);
if (numberOfCollidersFound == 0)
{
Pick(itemChunk, hit.point, spawnRotation);
}
}
}
void Pick(ItemChunk itemChunk, Vector3 positionToSpawn, Quaternion rotationToSpawn)
{
int randomIndex = Random.Range(0, itemsToPickFrom.Length);
GameObject item = itemsToPickFrom[randomIndex];
// this is one of the places I tried applying the random rotation
rotationToSpawn *= Quaternion.Euler(item.transform.rotation.x, item.transform.rotation.y, item.transform.rotation.z + Random.Range(0, 360));
GameObject clone = Instantiate(item, positionToSpawn, rotationToSpawn);
clone.transform.parent = itemChunk.transform;
Debug.Log(clone.transform.localScale);
}
Here is an image of what is going on
Is something wrong in my Quaternion Conversions ? Is this particular to Instantiation ? for practical issues I've had to put the Quad inside an Empty to make a prefab, the Quad has 0 rotations/transforms and the Quad has a 90 degree rotation.
Upvotes: 0
Views: 628
Reputation: 914
Try this:
rotationToSpawn = Quaternion.Euler(item.transform.rotation.x, item.transform.rotation.y, item.transform.rotation.z + Random.Range(-15, 15));
If I get what you're doing, you want the grass to have a slight rotation on the z axis. This should do it. If item already has a large z rotation, you can try this:
rotationToSpawn = Quaternion.Euler(item.transform.rotation.x, item.transform.rotation.y, Random.Range(-15, 15));
Upvotes: 1