【问题标题】:How can I reset a Vector3 position?如何重置 Vector3 位置?
【发布时间】:2015-10-07 05:21:22
【问题描述】:

我正在尝试编写一个实例化一行预制件的脚本。这是第一次工作,但之后每次它都会在 0x,0y,0z 处实例化一个,其余的在 30x-40x 之外。我尝试在 for 循环执行之前设置初始位置,然后使用 initalPos 变量重置位置,但这似乎不起作用。在我的代码中

    public class generator : MonoBehaviour {

    public int height = 0;
    public int width = 0;
    private Vector3 temp;
    public GameObject sprite;
    private Vector3 initialPos;


    void Start () 
    {
        initialPos = new Vector3(0,0,0);

        for(int i = 0; i < width; i++)
        {
            Instantiate (sprite, temp, Quaternion.identity);
            temp = sprite.transform.position;
            temp.x += 0.089f;
            sprite.transform.position = temp;
        }
        temp = initialPos;
    }
}

临时变量是我设置当前位置的值,所以我可以向它添加 0.089,这样我的精灵就会对齐。我正在尝试重置该值,以便它们每次都从 0x 开始排列。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您可以通过指定希望连续生成的预制件的数量而不是确切的宽度来简化代码。

    此外,不要将生成位置 x 值增加一个硬编码数字,而是使用 gameObject.transform.localScale.x

    例如:

    public GameObject Cube;
    
    void Start()
    {
        SpawnRow(Vector3.zero, 10);
    }
    
    void SpawnRow(Vector3 startPosition, int RowLength)
    {
        Vector3 currentPos = startPosition;
    
        for (int i = 0; i < RowLength; i++)
        {
            Instantiate(Cube, currentPos, Quaternion.identity);
            currentPos.x += Cube.transform.localScale.x;
        }
    }
    

    此外,如果您想做一些事情,例如在彼此旁边生成额外的行,您可以像这样调用 SpawnRow():

    void Start()
    {
        Vector3 currentPos = Vector3.zero;
    
        for (int i = 0; i < 3; i++)
        {
            SpawnRow(currentPos, 10);
            currentPos.z += Cube.transform.localScale.z;
        }
    }
    

    这将为您提供三行直接相邻的 10 个游戏对象。

    【讨论】:

    • 非常感谢!我不知道 localScale 或 Vector3.zero。解决了我的问题并教会了我一些东西。我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多