将对象旋转 90 度?

Rotate object by 90 degrees?

我知道这个问题已经被回答了 1000 次,但我只是不知道我应该如何编码。 我想要的只是当平台改变其在 x 或 z 轴上的位置时,然后将整个平台旋转 90 度。 我尝试使用 platform.transform.Rotate(0, 90, 0),所以我认为还有更多工作要做。 代码本身:

    public GameObject platform;
    public Transform lastPlatform;
    Vector3 lastPosition;
    Vector3 newPos;
    bool stop;

    private Quaternion rotationQuaternion;

    void Start()
    {
        lastPosition = lastPlatform.position;
        StartCoroutine(SpawnPlatforms());

    rotationQuaternion = transform.rotation;
    }

    void Update()
    {

    }

    IEnumerator SpawnPlatforms()
    {
        while (!stop)
        {
            GeneratePosition();

        Instantiate(platform, newPos, rotationQuaternion * Quaternion.identity);

            lastPosition = newPos;

            yield return new WaitForSeconds(0.1f);
        }
    }

    void GeneratePosition()
    {
        newPos = lastPosition;

        int rand = Random.Range(0, 2);

        if (rand > 0)
        {
            newPos.x += 1.5f;
        transform.rotation = rotationQuaternion * Quaternion.Euler(0, 90, 0); //one way i tried
        }
        else
        {
            newPos.z += 1.5f;
            platform.transform.Rotate(0, 90, 0) //another way I tried
        }
    }

感谢大家的帮助!

你可以使用它,它来自 Unity3D 文档。

https://docs.unity3d.com/ScriptReference/Transform-eulerAngles.html

据我所知,目前存在多个问题/不清楚的事情

  • 您每 0.1 秒旋转约 90°,因此在 1 秒内您旋转约 900°。对我来说,这听起来像是一种简单的禁食方式。
  • 您还旋转 transform 而不是平台
  • platform 似乎是资产中的 Prefab 所以旋转它没有意义

你可能想做

void GeneratePosition()
{
    newPos = lastPosition;

    int rand = Random.Range(0, 2);

    if (rand > 0)
    {
        newPos.x += 1.5f;
    }
    else
    {
        newPos.z += 1.5f;
    }

    // rather directly rotate the quaternion parameter
    // if you are going to do the same thing in both cases anyway I would rather extract it right away
    rotationQuaternion *= Quaternion.Euler(0, 90, 0);
}

然后还有

// Rotating by "Quaternion.idendity" has no effect
Instantiate(platform, newPos, rotationQuaternion);

对我来说这听起来还是很多,也许你会想看看 Object Pooling

我设法找到了问题的解决方案。也许对某人有帮助,所以给你:

public struct SpawnPoint
    {
        public Vector3 position;
        public Quaternion orientation;

        public void Step(float distance)
        {
            if (Random.value < 0.5)
            {
                position.x += distance;
                orientation = Quaternion.Euler(0, 90, 0);
            }
            else
            {
                position.z += distance;
                orientation = Quaternion.Euler(0, 0, 0);
            }

            //orientation = Quaternion.Euler(0, 90, 0) * orientation;
        }
    }

    void Start()
    {
        _spawn.position = lastPlatform.position;
        _spawn.orientation = transform.rotation;
    }

从现在开始,剩下要做的就是实例化:

var newPlatform = Instantiate(platform, _spawn.position, _spawn.orientation);

非常感谢 derHugo 为我提供了如何做到这一点的开始!