首页 > 解决方案 > Unity如何生成具有旋转速度的GameObject

问题描述

我想在按下空格键后生成具有旋转速度的块。我认为以下代码不起作用,因为它GameObject每次都会产生一个新代码。

public GameObject blockPrefab;
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Vector3 randomSpawnPosition = new Vector2(Random.Range(Player.screenHalfWidth, -Player.screenHalfWidth), 0);
        Vector3 randomSpawnRotation = new Vector3(0, 0, Random.Range(0, 360));
        GameObject block = Instantiate(blockPrefab, randomSpawnPosition, Quaternion.Euler(randomSpawnRotation));
        block.transform.parent = transform;

        // How do I set a rotation velocity here?
        block.transform.Rotate(new Vector3(0, 0, Random.Range(0, 30)* Time.deltaTime), Space.Self);
    }
}

我不确定该怎么做,因为所有示例都说要使用Rotate(),但据我所知,这在这种情况下永远行不通。

标签: c#unity3d

解决方案


将您的实例化与您的轮换分开。你在同一个“if”语句中做这两个。为实例化和旋转创建一个单独的脚本。将旋转脚本附加到“块”预制件上。

如果您要创建一个用于旋转预制件的新脚本,这里有一个 Rotator.cs Update() 方法的示例:

//...
void Update()
{
    transform.Rotate(new Vector3(0, 0, Random.Range(0, 30)* Time.deltaTime), Space.Self);
}
//...

推荐阅读