pgiz4/Assets/Scripts/LevelGenerator.cs

94 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using System.Collections.Generic;
public class LevelGenerator : MonoBehaviour
{
public GameObject platformPrefab;
public Transform playerTransform;
public int numberOfPlatforms = 5;
public float platformLength = 50f;
public GameObject coinPrefab;
public GameObject obstaclePrefab;
// Теперь будем хранить пары: платформа и список объектов на ней
private Dictionary<GameObject, List<GameObject>> platformItems = new Dictionary<GameObject, List<GameObject>>();
private List<GameObject> activePlatforms = new List<GameObject>();
private float spawnPosition = 0f;
void Start()
{
for (int i = 0; i < numberOfPlatforms; i++)
{
SpawnPlatform();
}
}
void Update()
{
if (playerTransform.position.z - platformLength > spawnPosition - (numberOfPlatforms * platformLength))
{
SpawnPlatform();
DeleteOldestPlatform();
}
}
private void SpawnPlatform()
{
GameObject newPlatform = Instantiate(platformPrefab, Vector3.forward * spawnPosition, Quaternion.Euler(0, 90, 0));
activePlatforms.Add(newPlatform);
// Создаем список для хранения объектов на этой платформе
platformItems[newPlatform] = new List<GameObject>();
PopulatePlatform(newPlatform);
spawnPosition += platformLength;
}
private void PopulatePlatform(GameObject platform)
{
int itemCount = Random.Range(3, 8);
for (int i = 0; i < itemCount; i++)
{
GameObject itemToSpawn = Random.Range(0, 3) > 0 ? coinPrefab : obstaclePrefab;
if (itemToSpawn != null)
{
float randomX = Random.Range(-4f, 4f);
float randomZ = Random.Range(-platformLength / 2 + 5, platformLength / 2 - 5);
Vector3 spawnPos = new Vector3(
platform.transform.position.x + randomX,
1f,
platform.transform.position.z + randomZ
);
// Создаем объект без родителя, чтобы избежать растягивания
GameObject newItem = Instantiate(itemToSpawn, spawnPos, Quaternion.identity);
// Добавляем созданный объект в список для последующего удаления
platformItems[platform].Add(newItem);
}
}
}
private void DeleteOldestPlatform()
{
GameObject platformToDelete = activePlatforms[0];
// Удаляем все объекты, связанные с этой платформой
if (platformItems.ContainsKey(platformToDelete))
{
foreach (GameObject item in platformItems[platformToDelete])
{
Destroy(item);
}
platformItems.Remove(platformToDelete);
}
// Удаляем саму платформу
Destroy(platformToDelete);
activePlatforms.RemoveAt(0);
}
}