Inheritance: MonoBehaviour
Ejemplo n.º 1
0
    public void GenerateNextChunk()
    {
        if (currentChunkNumber < currentLevel.TrackLength)             // keep generating chunks until you've exceeded number of chunks
        {
            LevelChunk currentLevelChunk = currentLevel.GetTrackAt(currentChunkNumber);

            if (currentLevelChunk.trackType >= trackChunkPrefabs.Count)
            {
                Debug.LogError("Level requested chunk type outside of range");
            }

            GameObject newChunkGameObject = Instantiate(
                trackChunkPrefabs[currentLevelChunk.trackType],
                nextChunkPosition,
                Quaternion.identity,
                transform) as GameObject;
            LevelChunkObject newChunkObject = newChunkGameObject.GetComponent <LevelChunkObject>();
            newChunkObject.Initialize(currentLevelChunk);
            currentChunkNumber++;

            UpdateNextChunkPosition();
            chunksCreated.Add(newChunkGameObject);
        }
        else
        {
            if (goalChunkInstance == null)
            {
                goalChunkInstance = Instantiate(
                    goalChunk,
                    nextChunkPosition,
                    Quaternion.identity,
                    transform) as GameObject;
            }
        }
    }
Ejemplo n.º 2
0
    void Start()
    {
        //initiate
        cam = FindObjectOfType <Camera>();
        float location = 0f;

        left   = new GameObject("");
        middle = new GameObject("");
        right  = new GameObject("");
        //get left chunk
        GameObject chunk      = GetRandomLevel();
        LevelChunk levelChunk = chunk.GetComponent <LevelChunk>();

        levelChunk.Awake();
        left      = ObjectPooler.Instance.SpawnFromPool(levelChunk.name, new Vector3(location, 0, 0), Quaternion.identity);
        location += left.GetComponent <LevelChunk>().getWidth();
        //get middle chunk
        chunk      = GetRandomLevel();
        levelChunk = chunk.GetComponent <LevelChunk>();
        levelChunk.Awake();
        middle = ObjectPooler.Instance.SpawnFromPool(levelChunk.name, new Vector3(location, 0, 0), Quaternion.identity);
        //get right chunk
        location  += middle.GetComponent <LevelChunk>().getWidth();
        chunk      = GetRandomLevel();
        levelChunk = chunk.GetComponent <LevelChunk>();
        levelChunk.Awake();
        right = ObjectPooler.Instance.SpawnFromPool(levelChunk.name, new Vector3(location, 0, 0), Quaternion.identity);
    }
    /// <summary>
    /// Spawns the level chunk from the object pool
    /// </summary>
    private void SpawnLevelChunk(bool forcePlainChunk = false)
    {
        // select a chunk from a random pool if not forced plain. There are more plain chunks than obstacle chunks.
        ObjectPool selectedPool;
        int        randomNum = Random.Range(0, 10);

        if (forcePlainChunk || randomNum < 1)
        {
            selectedPool = _objectPoolPlain;
        }
        else
        {
            int random = Random.Range(0, _availablePools.Length);
            selectedPool = _availablePools[random];
        }

        // get gameobject from pool.
        GameObject levelGO = selectedPool.GetGameObject();

        levelGO.transform.position = new Vector3(transform.position.x, transform.position.y, _currentPosZ);
        levelGO.SetActive(true);

        // increment the z position.
        LevelChunk chunk = levelGO.GetComponent <LevelChunk>();

        chunk.Init();
        _currentPosZ += chunk.Size;

        _levelChunks.Add(chunk);
    }
Ejemplo n.º 4
0
    public void AddChunk()
    {
        //Pick a random number between 0 and the number of level prefabs
        int randomIndex = Random.Range(0, levelPrefabs.Count);

        //Instantiates, created a copy or an instance, of a random level prefab and stores it as a chunk
        LevelChunk chunk = (LevelChunk)Instantiate(levelPrefabs[randomIndex]);

        chunk.transform.SetParent(this.transform, false);

        Vector3 spawnPosition = Vector3.zero;

        //If there are no prior added chunks in the list
        if (chunks.Count == 0)
        {
            //Assign position of first chunk
            spawnPosition = levelStartPoint.position;
        }
        else
        {
            //Use exit point from the most recently spawned chunk as the spawn point for a new chunk
            spawnPosition = chunks[chunks.Count - 1].exitPoint.position;
        }

        chunk.transform.position = spawnPosition;
        //Add the instanced chunk to the chunks list
        chunks.Add(chunk);
    }
Ejemplo n.º 5
0
    void ExpressNextChunk()
    {
        if (!allTeirsActive && curChunkY < curAstroid.teirs[curTeirIndex + 1].appearsAfter)
        {
            // increase to next teir
            curTeirIndex++;
            curDifficulty = curAstroid.teirs [curTeirIndex].difficulty;
            print("Moved to teir " + curTeirIndex + " with " + (curDifficulty + baseDifficulty) + " difficulty");
            if (curTeirIndex >= curAstroid.teirs.Length - 1)
            {
                allTeirsActive = true;
                print("All teirs now active");
            }
        }
        LevelChunk chunk     = GetChunk();
        int        xFlipSign = 1;

        if (Random.value > 0.5f)
        {
            xFlipSign = -1;
        }

        foreach (var levelObject in chunk.levelObjects)
        {
            Vector3 spawnPos = new Vector3(levelObject.pos.x * xFlipSign, levelObject.pos.y + curChunkY + initalChunkY, 1f);
            Instantiate(levelObject.prefab, spawnPos, Quaternion.identity, transform);
        }

        curChunkY -= chunk.chunkSize;
    }
Ejemplo n.º 6
0
    // Spawn a specific chunk
    void SpawnChunk(GameObject chunk)
    {
        Vector3 spawnPos = Vector3.zero;

        if (lastSpawnedChunk != null)
        {
            // Spawn following most recently spawned chunk
            spawnPos = lastSpawnedChunk.RightEnd();
        }
        else if (lastSpawnedChunk == null && mainCam != null)
        {
            // Default spawn point
            spawnPos = mainCam.ViewportToWorldPoint(Vector3.zero);
        }
        // Spawn the chunks and add it to the queue
        lastSpawnedChunk = Instantiate(chunk, new Vector3(spawnPos.x, spawnPos.y, 0.0f), Quaternion.identity).GetComponent <LevelChunk>();
        spawnedChunks.Enqueue(lastSpawnedChunk);
        // Increment the number of total chunks ever spawned
        totalChunksSpawned++;
        // Update the frequency of hard chunk spawns if the chunk milestone is surpassed
        if (totalChunksSpawned != 0 && totalChunksSpawned % chunkMilestone == 0)
        {
            if (hardChunkFreq > minHardChunkFreq)
            {
                hardChunkFreq--;
            }
        }
    }
Ejemplo n.º 7
0
    private void ClearChunk(LevelChunk chunk)
    {
        activeChunks.Remove(chunk);
        chunk.OnDespawn();

        chunk.ReturnToPool();
    }
Ejemplo n.º 8
0
    public void PlaceChunk()
    {
        LevelChunk toSpawn = placedChunks.Count > 0 ? GetRandomLevelChunk() : GetRandomStartChunk();

        if (toSpawn == null)
        {
            Debug.Log(lastChunkIndex);
            return;
        }
        // make new chunk
        LevelChunk newChunk = Instantiate(toSpawn, transform);

        Vector3 directionCheck = placeDirection;

        directionCheck.x *= newChunk.bounds.x;
        directionCheck.y *= newChunk.bounds.y;
        directionCheck.z *= newChunk.bounds.z;
        float directionLength = directionCheck.magnitude;

        if (placedChunks.Count > 0)
        {
            nextPlace += directionLength * placeDirection * 0.5f;
        }
        // place it properly
        newChunk.transform.localPosition = nextPlace;

        nextPlace += directionLength * placeDirection * 0.5f;

        placedChunks.Add(newChunk);
    }
Ejemplo n.º 9
0
    private void loadChunks()
    {
        rand = new System.Random();

        Vector3 ballPos = player.ballRef.position;

        float loadRadius = chunkSize * loadNumChunks;
        Rect  loadRect   = new Rect(ballPos.x - loadRadius, ballPos.y - loadRadius, loadRadius * 2f, loadRadius * 2f);

        for (int y = 0; y < loadNumChunks * 2; y++)
        {
            for (int x = 0; x < loadNumChunks * 2; x++)
            {
                Vector3 currChunk = new Vector3(Mathf.Floor(loadRect.xMin / chunkSize) + x, Mathf.Floor(loadRect.yMin / chunkSize) + y, 0f);
                if (!grid.ContainsKey(currChunk) && (currChunk.y > ground.position.y / chunkSize))
                {
                    LevelChunk chunk = (LevelChunk)Instantiate(chunkPrefab, currChunk * chunkSize, Quaternion.identity);
                    grid.Add(currChunk, chunk);

                    chunk.transform.parent = transform;

                    chunk.init(this);
                }
            }
        }
    }
    public ChunkyLevel GenerateLevel()
    {
        //First, we generate the direction map. How do we get from the start to the end?
        LevelChunk[,] template = new LevelChunk[widthInChunks, heightInChunks];
        //Pick a random top tile for start and a random bottom tile for exit
        int sx = Random.Range(0, widthInChunks); int sy = 0;
        int osx = sx; int osy = sy;
        int ex = Random.Range(0, widthInChunks); int ey = heightInChunks - 1;
        //Now randomly map from the start to the finish. We're basing our approach on how
        //Spelunky did things, but pretty loosely - the general idea is there.
        //If you want to read more: http://tinysubversions.com/spelunkyGen/index.html
        int rounds = 0;
        int dir    = Random.Range(-1, 2);

        bool[] lastDir = new bool[] { false, true, false, true };

        //We store this in the level just for convenience so we can calculate some metrics
        List <Vector2> path = new List <Vector2>();

        path.Add(new Vector2(sx, sy));

        while ((sx != ex || sy != ey) && rounds++ < 100)
        {
            if (dir < 0 && sx > 0)
            {
                template[sx, sy] = FindChunk(lastDir[0], lastDir[1], lastDir[2], true);
                sx--;
                path.Add(new Vector2(sx, sy));
                lastDir = new bool[] { false, true, false, false };
                if (sy < heightInChunks - 1)
                {
                    dir = new int[] { dir, dir, 0 }
                }
Ejemplo n.º 11
0
    public void RemoveOldestChunk()
    {
        //Takes the first chunk from the chunks list, removes it from the list then destroys its respective game object
        LevelChunk oldestChunk = chunks[0];

        chunks.Remove(oldestChunk);
        Destroy(oldestChunk.gameObject);
    }
Ejemplo n.º 12
0
    static public void RebuildPaths()
    {
        //first see if we need to connect the level chunk starting and ending nodes (client only)
        if (Network.isClient)
        {
            LevelChunk[] allChunks = GameObject.Find("LevelContainer").GetComponentsInChildren <LevelChunk>();
            int          numChunks = allChunks.Length;

            foreach (LevelChunk chunk in allChunks)
            {
                int chunkNumber = chunk.mChunkNumber;
                if (chunkNumber != numChunks - 1)                 //ignore the last chunk
                {
                    LevelChunk nextChunk = PathUtils.GetChunkNumberFromArray(allChunks, chunkNumber + 1);
                    PathUtils.ConnectChunkPathNodes(chunk.gameObject, nextChunk.gameObject);
                }
            }
        }


        mFirstNode = null;

        //get the first path node
        foreach (GameObject node in GameObject.FindGameObjectsWithTag("PathNode"))
        {
            if (node.GetComponent <PathNode>().mPrevNode == null)
            {
                mFirstNode = node;
            }

            node.GetComponent <PathNode>().RecalcPathWidth();
        }

        if (!mFirstNode)
        {
            Debug.LogError("Could not find first path node");
        }

        //loop over all nodes
        mNumPathNodes = 0;
        PathNode curnode = mFirstNode.GetComponent <PathNode>();

        while (curnode != null)
        {
            //set the node number
            curnode.SetNumber(mNumPathNodes);
            mNumPathNodes++;

            if (curnode.mNextNode)             //see if there is a next node
            {
                curnode = curnode.mNextNode.GetComponent <PathNode>();
            }
            else             //or if this is the last node
            {
                curnode = null;
            }
        }
    }
Ejemplo n.º 13
0
 private void AddChunk(LevelChunk chunk)
 {
     foreach (var newObject in chunk.ContainedObjects)
     {
         var instance = PoolManager.Instance.Spawn(newObject.Object);
         instance.transform.position = newObject.Position.Y(newObject.Position.y + currentHeight);
     }
     currentHeight += chunk.Height;
 }
Ejemplo n.º 14
0
 void Update()
 {
     CheckUnloadChunk();
     if (loadedChunks.Count < numberOfChunksToLoad)
     {
         SpawnRandomChunk();
     }
     currentChunk = loadedChunks[0];
 }
Ejemplo n.º 15
0
    public void OnSceneGUI()
    {
        LevelChunk chunk = target as LevelChunk;

        if (chunk == null)
        {
            return;
        }

        Handles.DrawWireCube(chunk.transform.position, chunk.bounds);
    }
 /// <summary>
 /// Resets this instance.
 /// </summary>
 public void Reset()
 {
     for (int i = _levelChunks.Count - 1; i >= 0; i -= 1)
     {
         LevelChunk chunk = _levelChunks[i];
         chunk.gameObject.SetActive(false);
         chunk.gameObject.transform.position = Vector3.zero;
         _levelChunks.Remove(chunk);
     }
     _currentPosZ = 0.0f;
     _canSpawn    = false;
 }
Ejemplo n.º 17
0
    void SpawnChunk()
    {
        LevelChunk newChunk      = _chunks[Random.Range(0, _chunks.Length)];
        Vector3    spawnPosition = new Vector3((_currentChunk.Position.x + _currentChunk.Size.x / 2f) + (newChunk.Size.x / 2f) + 5,
                                               _currentChunk.Position.y,
                                               _currentChunk.Position.z);

        _currentChunk    = Instantiate(newChunk, spawnPosition, Quaternion.identity);
        _spawnThreshold += newChunk.Size.x;

        _currentChunk.transform.SetParent(transform);
    }
Ejemplo n.º 18
0
    // Use this for initialization
    void Start()
    {
        leftChunks  = new List <Transform>();
        rightChunks = new List <Transform>();
        upChunks    = new List <Transform>();
        downChunks  = new List <Transform>();
        foreach (Transform chunk in levelChunks)
        {
            LevelChunk thisChunk = chunk.GetComponent <LevelChunk>();
            if (thisChunk.Right())
            {
                rightChunks.Add(chunk);
            }
            if (thisChunk.Left())
            {
                leftChunks.Add(chunk);
            }
            if (thisChunk.Up())
            {
                upChunks.Add(chunk);
            }
            if (thisChunk.Down())
            {
                downChunks.Add(chunk);
            }
        }

        for (int i = 0; i < size - 1; i++)
        {
            //place chunks around the border
            //placed[i, 0] = true;
            //placed[i, (size - 1)] = true;
            //placed[0, i] = true;
            //placed[(size - 1), i] = true;

            Transform leftChunk  = Instantiate(leftWall);
            Transform rightChunk = Instantiate(leftWall);
            Transform upChunk    = Instantiate(bottomWall);
            Transform downChunk  = Instantiate(bottomWall);

            Vector3 origin = new Vector3((-(int)Mathf.Round(size / 2)) * chunkSize, 0.0f, (-(int)Mathf.Round(size / 2)) * chunkSize);

            leftChunk.transform.position  = new Vector3(0, 2.5f, i * chunkSize) + origin;
            rightChunk.transform.position = new Vector3((size - 1) * chunkSize, 2.5f, i * chunkSize) + origin;
            upChunk.transform.position    = new Vector3(i * chunkSize, 2.5f, 0) + origin;
            downChunk.transform.position  = new Vector3(i * chunkSize, 2.5f, (size - 1) * chunkSize) + origin;
        }

        PlaceChunk((int)Mathf.Round(size / 2), (int)Mathf.Round(size / 2), DIRECTION.UP);

        //FindObjectOfType<CoverManager>().RemakeCover();
    }
Ejemplo n.º 19
0
    void ExpressNextChunk()
    {
        LevelChunk chunk = GetChunk();

        foreach (var levelObject in chunk.levelObjects)
        {
            Vector3    spawnPos = new Vector3(levelObject.pos.x + curChunkX, levelObject.pos.y, 1f);
            GameObject GO       = (GameObject)Instantiate(levelObject.prefab, spawnPos, Quaternion.identity, transform);
            activeObjects.Add(GO);
        }

        curChunkX += chunk.chunkSize;
    }
    /// <summary>
    /// Culls the old chunks when they are behind the camera.
    /// </summary>
    private void CullOldChunks()
    {
        for (int i = _levelChunks.Count - 1; i >= 0; i -= 1)
        {
            LevelChunk chunk = _levelChunks[i];

            if (chunk.FarEdge < _cameraContoller.PosZ)
            {
                chunk.gameObject.SetActive(false);
                _levelChunks.Remove(chunk);
            }
        }
    }
Ejemplo n.º 21
0
    public void SpawnRandomForegroundObject(LevelChunk chunk)
    {
        if (currentBiome == null || currentBiome.foregroundPrefabs.Length == 0)
        {
            return;
        }
        var index            = Random.Range(0, currentBiome.foregroundPrefabs.Length);
        var foregroundObject = Instantiate(currentBiome.foregroundPrefabs[index], chunk.chunkEnd.transform);

        foregroundObject.transform.eulerAngles = Vector3.zero;
        var moveBy = chunk.chunkEnd.transform.position - foregroundObject.spawnConnector.transform.position;

        foregroundObject.transform.position += moveBy;
    }
Ejemplo n.º 22
0
    public void DeleteBehind(Vector3 pos)
    {
        for (int i = placedChunks.Count - 1; i >= 0; --i)
        {
            LevelChunk c = placedChunks[i];

            float dot = Vector3.Dot(pos - c.transform.position, -1.0f * placeDirection);
            if (dot > 0)
            {
                continue;
            }

            Destroy(c.gameObject);
            placedChunks.RemoveAt(i);
        }
    }
Ejemplo n.º 23
0
	public Level Generate(int numChunks)
	{
		Level newLevel = new Level();
		for (int i = 0; i < numChunks; i++)
		{
			bool doesSpawnItem = Random.Range(0.0f, 1.0f) < itemSpawnRatio;
			bool doesSpawnEnemy = Random.Range(0.0f, 1.0f) < enemySpawnRatio;
			LevelChunk newChunk = new LevelChunk(
											Random.Range(0, numTrackTypes), 
											(doesSpawnItem ? Random.Range(0, numItemTypes) : -1), 
											(doesSpawnEnemy ? Random.Range(0, numEnemyTypes) : -1));

			newLevel.AddTrack(newChunk);
		}
		return newLevel;
	}
Ejemplo n.º 24
0
 void Update()
 {
     //if a middle chunk exists and the camera's right bounds exceeds the middle of it, shuffle
     if (middle.name != "")
     {
         if (cam.ViewportToWorldPoint(new Vector3(1, 0, -10)).x >= middle.transform.position.x + middle.GetComponent <LevelChunk>().getWidth() / 2)
         {
             GameObject chunk      = GetRandomLevel();
             LevelChunk levelChunk = chunk.GetComponent <LevelChunk>();
             left   = middle;
             temp   = right;
             right  = ObjectPooler.Instance.SpawnFromPool(levelChunk.name, right.transform.position + new Vector3(temp.GetComponent <LevelChunk>().getWidth(), 0, 0), Quaternion.identity);
             middle = temp;
         }
     }
 }
Ejemplo n.º 25
0
    private LevelChunk SpawnChunk(LevelChunk chunk, LevelChunk prevChunk)
    {
        var spawnedChunk = Instantiate(chunk, transform);
        var startPos     = spawnedChunk.chunkStart.transform.position;
        var endPos       = prevChunk ? prevChunk.chunkEnd.transform.position : Vector3.zero;
        var moveBy       = prevChunk ? endPos - startPos : Vector3.zero;

        spawnedChunk.transform.position += moveBy;
        spawnedChunks.Add(spawnedChunk);

        // Also spawn foreground object on the chunk
        foreground.SpawnRandomForegroundObject(spawnedChunk);

        // And change color according to biome settings
        spawnedChunk.SetColor(currentBiome.groundColor);
        return(spawnedChunk);
    }
Ejemplo n.º 26
0
    void ScanMap()
    {
        foreach (Texture2D map in mapData)
        {
            GameObject newMap = new GameObject(map.name);
            processedTiles.Clear();
            for (int i = 0; i < map.width; i++)
            {
                for (int j = 0; j < map.height; j++)
                {
                    GenerateTile(map, newMap, j, i);
                }
            }

            switch (type)
            {
            case MapType.CHUNK:

                GameObject baseTiles = new GameObject("Base Tiles");
                baseTiles.transform.SetParent(newMap.transform);
                baseTiles.AddComponent <SetPiece>();
                SetPiece piece = baseTiles.GetComponent <SetPiece>();
                piece.grid.AddRange(processedTiles);
                piece.Width  = map.width;
                piece.Height = map.height;

                newMap.AddComponent <LevelChunk>();
                LevelChunk tempChunk = newMap.GetComponent <LevelChunk>();
                tempChunk.baseTiles = piece;
                Object prefab = PrefabUtility.CreatePrefab("Assets/Resources/Prefabs/LevelPrefabs/LevelChunks/" + map.name + ".prefab", newMap);
                //AssetDatabase.CreateAsset(newMap, "Assets/Resources/Prefabs/LevelPrefabs/LevelChunks/" + map.name);
                break;

            case MapType.SETPIECE:
                newMap.AddComponent <SetPiece>();
                SetPiece tempPiece = newMap.GetComponent <SetPiece>();
                tempPiece.grid.AddRange(processedTiles);
                tempPiece.Width  = map.width;
                tempPiece.Height = map.height;
                AssetDatabase.CreateAsset(newMap, "Assets/Resources/Prefabs/LevelPrefabs/SetPieces/" + map.name);
                break;
            }
        }
    }
Ejemplo n.º 27
0
    public void Initialize(LevelChunk levelChunk)
    {
        m_levelChunk = levelChunk;

        // trigger spawns
        List <PrefabDrop> dropPoints = new List <PrefabDrop>();

        dropPoints.AddRange(transform.GetComponentsInChildren <PrefabDrop>());
        for (int i = 0; i < dropPoints.Count; i++)
        {
            if (dropPoints[i].thingsToSpawn == TrackGenerator.SpawnerType.ITEM)
            {
                if (m_levelChunk.itemType >= 0)
                {
                    dropPoints[i].DropPrefab(TrackGenerator.Instance.items[m_levelChunk.itemType].gameObject);
                }
            }
            else if (dropPoints[i].thingsToSpawn == TrackGenerator.SpawnerType.ENEMY)
            {
                if (m_levelChunk.enemyType >= 0)
                {
                    dropPoints[i].DropPrefab(TrackGenerator.Instance.enemies[m_levelChunk.enemyType].gameObject);
                }
            }
            else
            {
                if (dropPoints[i].transform.position.x < 0.0f)
                {
                    dropPoints[i].DropPrefab(TrackGenerator.Instance.footprintL.gameObject);
                }
                else
                {
                    dropPoints[i].DropPrefab(TrackGenerator.Instance.footprintR.gameObject);
                }
            }
        }
    }
Ejemplo n.º 28
0
    /// <summary>
    /// Spawn a random chunk and place it just beyond the last chunk.
    /// </summary>
    void SpawnRandomChunk()
    {
        int numOfPrefabs = prefabChunks.Length;

        if (numOfPrefabs <= 0)
        {
            return;
        }

        Vector3 pos = Vector3.zero;

        if (loadedChunks.Count > 0)
        {
            pos = loadedChunks[loadedChunks.Count - 1].endOfChunk.position;
        }

        LevelChunk prefab   = prefabChunks[Random.Range(0, numOfPrefabs)];
        LevelChunk newChunk = Instantiate(prefab, pos, Quaternion.identity);

        // flip it:
        //if(Random.Range(0,100) > 50) newChunk.transform.localScale = new Vector3(-1, 1, 1);

        loadedChunks.Add(newChunk);
    }
Ejemplo n.º 29
0
 public void AddTrack(LevelChunk c)
 {
     tracks.Add(c);
 }
Ejemplo n.º 30
0
 private void Start()
 {
     _currentChunk = FindObjectOfType <LevelChunk>();
     _bgChunk      = FindObjectOfType <BGChunk>();
 }