Untitled
unknown
plain_text
10 months ago
3.4 kB
1
Indexable
using System.Collections; using System.Collections.Generic; using System.Linq; using Unity.VisualScripting; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; public class PickupSpawner : MonoBehaviour { private LaneManager laneManager; ObjectPooler op; CarSpawner carSpawner; public List<GameObject> pickups; [SerializeField] private float minSpawnDistance = 2f; // Minimum allowed distance between colliders [SerializeField] LayerMask layersEnemyCannotSpawnOn; [SerializeField] float radius = 1f; Vector2 spawnPos = Vector2.zero; bool canSpawnHere = false; int randomPrefabIndex = 0; private void Awake() { carSpawner = GetComponent<CarSpawner>(); laneManager = FindObjectOfType<LaneManager>(); } void Start() { op = ObjectPooler.instance; if(laneManager.MainLaneCount == 2) { RemoveSpecificPickups(); } StartCoroutine(SpawnPickups()); } void Update() { } void RemoveSpecificPickups() { } IEnumerator SpawnPickups() { while (true) { randomPrefabIndex = Random.Range(0, pickups.Count); GetRandomSpawnPosition(); canSpawnHere = CheckForValidPosition(spawnPos); if (canSpawnHere) { op.SpawnFromPool(pickups[randomPrefabIndex].tag, spawnPos); carSpawner.items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList()); } float time = Random.Range(5f, 10f); yield return new WaitForSeconds(1f); } } private Vector2 GetRandomSpawnPosition() { int randomLaneIndex = Random.Range(0, laneManager.GetCurrentLaneCount()); float laneWidth = laneManager.GetCurrentLaneWidth(randomLaneIndex); float middleLanePosition = laneManager.GetLanePosition(randomLaneIndex) + laneWidth / 2f; spawnPos = new Vector2(middleLanePosition, Random.Range(10.25f, 50f) + minSpawnDistance); return spawnPos; } bool CheckForValidPosition(Vector2 spawnPosition) { bool isSpawnPosValid = false; int attemptCount = 0; int maxAttempts = 200; Collider2D[] colliders; while (!isSpawnPosValid && attemptCount < maxAttempts) { bool isInvalidCollision = false; colliders = Physics2D.OverlapCircleAll(spawnPos, radius); foreach (Collider2D col in colliders) { if (((1 << col.gameObject.layer) & layersEnemyCannotSpawnOn) != 0) { // Invalid collision found isInvalidCollision = true; break; } } if (!isInvalidCollision) { isSpawnPosValid = true; } attemptCount++; } // If no invalid collisions found, spawn position is valid if (!isSpawnPosValid) { return false; } return true; } }
Editor is loading...
Leave a Comment