99 lines
2.8 KiB
C#
99 lines
2.8 KiB
C#
using UnityEngine;
|
|
|
|
public class ObjectSpawner : MonoBehaviour
|
|
{
|
|
[Header("Master Prefab")]
|
|
public GameObject masterPrefab;
|
|
|
|
[Header("Data Koleksi")]
|
|
public DataSayur[] koleksiData;
|
|
|
|
[Header("Settings Level (Atur di Inspector)")]
|
|
public float spawnInterval = 2.5f; // Jeda antar sayur
|
|
public float fallSpeed = 300f; // Kecepatan jatuh sayur
|
|
public float batasKiri = -500f;
|
|
public float batasKanan = 500f;
|
|
public float spawnHeight = 600f;
|
|
|
|
private float timer;
|
|
private float lastX;
|
|
private bool isSpawning = false;
|
|
|
|
void Start()
|
|
{
|
|
isSpawning = false; // Tunggu perintah GameManager
|
|
}
|
|
|
|
// FUNGSI SAKTI: Dipanggil GameManager setelah Countdown
|
|
public void MulaiHujanSayur()
|
|
{
|
|
isSpawning = true;
|
|
|
|
// 1. LANGSUNG MUNTAHKAN SATU SAYUR (Tanpa Jeda)
|
|
SpawnObject();
|
|
|
|
// 2. Reset timer ke 0 agar sayur kedua muncul setelah 'spawnInterval'
|
|
timer = 0;
|
|
}
|
|
|
|
public void BerhentiHujanSayur()
|
|
{
|
|
isSpawning = false;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (!isSpawning) return;
|
|
|
|
timer += Time.deltaTime;
|
|
if (timer >= spawnInterval)
|
|
{
|
|
SpawnObject();
|
|
timer = 0;
|
|
}
|
|
}
|
|
|
|
void SpawnObject()
|
|
{
|
|
if (masterPrefab == null || koleksiData == null || koleksiData.Length == 0) return;
|
|
|
|
int randomIndex = Random.Range(0, koleksiData.Length);
|
|
DataSayur dataTerpilih = koleksiData[randomIndex];
|
|
|
|
if (dataTerpilih != null)
|
|
{
|
|
// Logika Jalur (Lane) tetap sama
|
|
float lebarTotal = batasKanan - batasKiri;
|
|
float lebarPerJalur = lebarTotal / 5f;
|
|
float randomX = 0;
|
|
bool posisiKetemu = false;
|
|
int percobaan = 0;
|
|
|
|
while (!posisiKetemu && percobaan < 10)
|
|
{
|
|
int jalurRandom = Random.Range(0, 5);
|
|
randomX = batasKiri + (jalurRandom * lebarPerJalur) + (lebarPerJalur / 2f);
|
|
if (Mathf.Abs(randomX - lastX) > 200f) posisiKetemu = true;
|
|
percobaan++;
|
|
}
|
|
lastX = randomX;
|
|
|
|
// Eksekusi Spawn
|
|
Vector2 spawnPos = new Vector2(randomX, spawnHeight);
|
|
GameObject newObj = Instantiate(masterPrefab, transform.parent);
|
|
|
|
RectTransform rt = newObj.GetComponent<RectTransform>();
|
|
if (rt != null) rt.anchoredPosition = spawnPos;
|
|
|
|
// KIRIM DATA & KECEPATAN KE ITEM
|
|
ItemProperty prop = newObj.GetComponent<ItemProperty>();
|
|
if (prop != null)
|
|
{
|
|
prop.dataItem = dataTerpilih;
|
|
// Kita kirim fallSpeed dari Inspector Spawner ke Item
|
|
prop.fallSpeed = this.fallSpeed;
|
|
prop.Inisialisasi();
|
|
}
|
|
}
|
|
}
|
|
} |