设置3D对象的生成位置

时间:2017-05-17 05:53:11

标签: c# unity3d

我正在制作一个无尽的亚军风格的游戏,其中地砖在玩家面前随机无休止地产生,并且在玩家后面一定距离后自行删除,这一切都很好并且不过个人意图瓷砖在彼此内部产生大约一半,并且尽管我尝试调试我的代码,但我似乎无法影响它们。理想情况下,我希望代码完全按照它正在进行的操作,但是tile会端到端而不是在彼此内部生成。

非常感谢任何帮助。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Tile_Manager : MonoBehaviour
{

    public GameObject[] tilePrefabs;

    private Transform playerTransform;
    private float spawnZ =  5.0f;
    private float tileLength = 5.0f;
    private float safeZone = 7.0f;
    private int amtTilesOnScreen = 10;
    private int lastPrefabIndex = 0;

    private List<GameObject> activeTiles;
    // Use this for initialization
    void Start () {
        activeTiles = new List<GameObject>();
        playerTransform = GameObject.FindGameObjectWithTag ("Player").transform;

        for (int i = 0; i < amtTilesOnScreen; i++)
        {
            if (i < 2)
                SpawnTile(0);
            else
                SpawnTile();
        }
    }

    // Update is called once per frame
    void Update () {
        if (playerTransform.position.z - safeZone > (spawnZ - amtTilesOnScreen * tileLength))
        {
            SpawnTile();
            DeleteTile();
        }

    }

    private void SpawnTile(int prefabIndex = -1)
    {
        GameObject go;
        if (prefabIndex == -1)
            go = Instantiate(tilePrefabs[RandomPrefabIndex()]) as GameObject;
        else
            go = Instantiate(tilePrefabs[prefabIndex]) as GameObject;
        go.transform.SetParent(transform);
        go.transform.position = Vector3.forward * spawnZ;
        spawnZ += tileLength;
        activeTiles.Add (go);
    }

    private void DeleteTile()
    {
        Destroy(activeTiles [0]);
        activeTiles.RemoveAt (0);
    }

    private int RandomPrefabIndex()
    {
        if (tilePrefabs.Length <= 1)
            return 0;

        int randomIndex = lastPrefabIndex;
        while (randomIndex == lastPrefabIndex)
        {
            randomIndex = Random.Range(0, tilePrefabs.Length);
        }

        lastPrefabIndex = randomIndex;
        return randomIndex;
    }
}

stacked tiles

2 个答案:

答案 0 :(得分:1)

您需要考虑瓷砖的长度。尝试更改此

go.transform.position = Vector3.forward * spawnZ;

到这个

go.transform.position = Vector3.forward * (spawnZ + tileLength / 2);

将图块长度的一半添加到生成位置。

答案 1 :(得分:0)

你不想要吗

go.transform.Translate(Vector3.forward * spawnZ);

不是位置?

当你产生相对于世界坐标系的东西时。 https://docs.unity3d.com/ScriptReference/Transform.Translate.html