C# 随意砍伐树木?

C# 随意砍伐树木?,c#,unity3d,C#,Unity3d,我不知道如何让一棵Y轴旋转的树在砍倒后倒下。我想让它垂直于地面(90度),但我想让它随机落在哪个方向 枢轴位于树的底部,因此如果我只是将Z轴旋转90度,那么它看起来会掉落,但我想随机化方向,我尝试了一些方法,但没有达到我预期的效果: public void Fall(float duration) { int xOrZ = Random.Range(0, 1); float randomRot = Random.Range(0,90); Vector3 rotation

我不知道如何让一棵Y轴旋转的树在砍倒后倒下。我想让它垂直于地面(90度),但我想让它随机落在哪个方向

枢轴位于树的底部,因此如果我只是将Z轴旋转90度,那么它看起来会掉落,但我想随机化方向,我尝试了一些方法,但没有达到我预期的效果:

public void Fall(float duration)
{
    int xOrZ = Random.Range(0, 1);
    float randomRot = Random.Range(0,90);

    Vector3 rotation = Vector3.zero;

    if (xOrZ == 0)
        rotation = new Vector3(90, 0, randomRot);
    else
        rotation = new Vector3(randomRot, 0, 90);

    mTransform.DORotate(rotation, duration);
}

我想如果我确定其中一个轴是90,那么它将始终落在地上,但这根本不起作用。

由于对象的轴位于底部,因此更容易将树游戏对象的
向上变换。您可以使用Unity的
Random.InsideUnitIcircle
拾取单位圆内的点。这将返回一个
Vector2
,然后您可以将每个组件与右向量和前向量相乘,以找到树下落时的尖端位置。现在,树对象的位置和落点之间的向量应该是树对象的新上向量。然后,您可以运行一个简单的协程,将树对象的上方向向量映射到新计算的上方向向量。
Lerp
允许您定义持续时间,并且当所需的上方向向量和当前上方向向量之间的距离低于某个阈值时,您可以切断协程。如果您使用此代码并按需要调用Fall函数,它将正常工作:

    using System.Collections; // for IEnumerator

    public GameObject treeObject; // assuming this is your tree object

    public void Fall(float duration)
    {
        // pick a random point on the circle to match the up vector
        Vector2 pointOnCircle = UnityEngine.Random.insideUnitCircle * treeObject.transform.localScale.y;

        // find the fall point, assuming the pivot of the object is at the bottom
        Vector3 fallPoint = treeObject.transform.position + 
            pointOnCircle.x * treeObject.transform.right + 
            pointOnCircle.y * treeObject.transform.forward;

        // find the target up vector
        Vector3 updatedUpVector = Vector3.Normalize(fallPoint - treeObject.transform.position);

        // Start the coroutine to tilt the up vector to the desired target
        StartCoroutine(UpdateUpVector(treeObject, updatedUpVector, duration, 0.001f));
    }

    public IEnumerator UpdateUpVector(GameObject target, Vector3 upVector, float duration, float threshold = 0.001f)
    {
        // the target vector and up vector would get closer to each other until the threshold is hit
        while(Vector3.Distance(upVector, target.transform.up) > threshold)
        {
            target.transform.up = Vector3.Lerp(target.transform.up, upVector, duration * Time.deltaTime);
            yield return new WaitForEndOfFrame();
        }
    }
上面的代码使用轴位于底部的圆柱体生成。请注意,树正朝着树对象的
变换位置周围的单位圆上的随机点下落。