Exemple #1
0
    // Create a new tile above the player
    private void SpawnTile()
    {
        int randomIndex = 0;

        for (int i = 0; i < tilePrefabs.Length; i++)
        {
            randomIndex = Random.Range(0, tilePrefabs.Length);

            if (randomIndex != lastTileIndex)
            {
                lastTileIndex = randomIndex;
                break;
            }
        }

        GameObject ground;

        ground = Instantiate(tilePrefabs[randomIndex]) as GameObject;
        ground.transform.SetParent(transform);
        ground.transform.position = new Vector3(-100.0f, 0.0f, spawnZ);

        for (int i = 0; i < maxProps; i++)
        {
            // 100 * 100 * 50
            Vector3 meshSize = new Vector3(100.0f, 100.0f, tileLength);

            TileGrid grid = ground.GetComponent <TileGrid>();

            Vector3    randomPosition = new Vector3(Random.Range(meshSize.x * -1 + limitX, meshSize.x - limitX), grid.height, Random.Range(spawnZ, spawnZ + meshSize.z));
            RaycastHit hitInfo;
            Ray        ray = new Ray();
            ray.origin    = randomPosition;
            ray.direction = ground.transform.up * -1;

            if (Physics.Raycast(ray, out hitInfo))
            {
                if (hitInfo.transform.tag == "Ground")
                {
                    GameObject randomProp;
                    int        randomPropsIndex = Random.Range(0, tileProps.Length);

                    randomProp = Instantiate(tileProps[randomPropsIndex]) as GameObject;

                    randomProp.transform.SetParent(ground.transform);

                    Vector3 calculatedPosition = new Vector3(randomPosition.x, hitInfo.transform.GetComponent <Terrain>().SampleHeight(randomPosition), randomPosition.z);
                    var     finalPosition      = grid.GetNearestPointOnGrid(calculatedPosition);
                    randomProp.transform.position = finalPosition;
                    randomProp.transform.Rotate(new Vector3(0, 1, 0) * Random.Range(0.0f, 360.0f));
                }
            }
        }

        spawnZ += tileLength;
        activeTiles.Add(ground);
    }