/// <summary> /// Spawns new chunk, then adds the chunk's children to the game. /// </summary> private void SpawnChunk() { float gapSizeMin = 1; float gapSizeMax = 2; float gapSize = Random.Range(gapSizeMin, gapSizeMax); Vector3 pos = new Vector3(-5, -3, 0); if (_chunks.Count > 0) { if (chunkCount < 6) // spawn chunks in order { chunkIndex++; } else // then randomly select them { chunkIndex = Random.Range(1, prefabs.Length); } pos.x = _chunks[_chunks.Count - 1].rightEdge.position.x + gapSize; pos.y = _chunks[_chunks.Count - 1].rightEdge.position.y; minLimit = pos.y - 110; } else { // spawn first pill pill.Spawn(_player.transform.position); } #region Add Chunk and it's children PetzakChunk chunk = Instantiate(prefabs[chunkIndex], pos, Quaternion.identity); _chunks.Add(chunk); PetzakPlatform[] newplatforms = chunk.GetComponentsInChildren <PetzakPlatform>(); foreach (PetzakPlatform p in newplatforms) { _platforms.Add(p.GetComponent <PetzakAABB>()); } PetzakSpring[] newsprings = chunk.GetComponentsInChildren <PetzakSpring>(); foreach (PetzakSpring s in newsprings) { _springs.Add(s.GetComponent <PetzakAABB>()); } PetzakSpikes[] newspikes = chunk.GetComponentsInChildren <PetzakSpikes>(); foreach (PetzakSpikes s in newspikes) { _spikes.Add(s.GetComponent <PetzakAABB>()); } #endregion chunkCount++; }
/// <summary> /// Removes chunks (and respawns lifepill) if they are off the left side of the screen. /// </summary> private void RemoveOffScreenChunks() { float limitX = FindScreenLeftX(); for (int i = _chunks.Count - 1; i >= 0; i--) { if (_chunks[i].rightEdge.position.x < limitX) { PetzakChunk chunk = _chunks[i]; // remove this chunk's platforms from the game PetzakPlatform[] deadPlatforms = chunk.GetComponentsInChildren <PetzakPlatform>(); foreach (PetzakPlatform platform in deadPlatforms) { _platforms.Remove(platform.GetComponent <PetzakAABB>()); } // remove this chunk's springs from the game PetzakSpring[] deadSprings = chunk.GetComponentsInChildren <PetzakSpring>(); foreach (PetzakSpring spring in deadSprings) { _springs.Remove(spring.GetComponent <PetzakAABB>()); } // remove this chunk's spikes from the game PetzakSpikes[] deadSpikes = chunk.GetComponentsInChildren <PetzakSpikes>(); foreach (PetzakSpikes spike in deadSpikes) { _spikes.Remove(spike.GetComponent <PetzakAABB>()); } // remove the chunk from the game _chunks.RemoveAt(i); Destroy(chunk.gameObject); // update score on hud var mesh = scoreText.GetComponent <TextMesh>(); mesh.text = score++.ToString(); } } // respawn pill if beyond limit bool pillIsBehindPlayer = lifePill.transform.position.x > lifePill.transform.position.x; if (lifePill.transform.position.x < limitX && pillIsBehindPlayer) { Debug.Log(lifePill.transform.position.x + " " + limitX); pill.Spawn(_player.transform.position); } }