试图在实例化的预制件上应用Z旋转,但效果不理想。

问题描述 投票:0回答:1

我正在程序化地通过射线投射到地形表面来生成草块,为了让它们看起来更有机,我想在Z轴上添加一个随机旋转,但我的每一次尝试都会让草块完全疯狂地旋转。

如果没有随机的Z旋转,草块在地形上是很好的,但却排列在一起,感觉不是很有机。

    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);
}

这里有一张图片,是正在发生的事情 enter image description here

我的四元组转换有什么问题吗?我的四边形转换是否有问题?

c# unity3d rotation quaternions raycasting
1个回答
1
投票

试试这个。

rotationToSpawn = Quaternion.Euler(item.transform.rotation.x, item.transform.rotation.y, item.transform.rotation.z + Random.Range(-15, 15));

如果我明白你的意思 你想让草块在Z轴上有轻微的旋转。这应该可以做到。如果项目已经有很大的z轴旋转,你可以试试这个。

rotationToSpawn = Quaternion.Euler(item.transform.rotation.x, item.transform.rotation.y, Random.Range(-15, 15));
© www.soinside.com 2019 - 2024. All rights reserved.