106 lines
2.9 KiB
C#
106 lines
2.9 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
[CreateAssetMenu(menuName = project_name + "/" + nameof(SpawnerTile))]
|
|
public class SpawnerTile : LevelTile
|
|
{
|
|
[SerializeField]
|
|
private GameObject _prefab;
|
|
[SerializeField]
|
|
private bool _spawnOnStart;
|
|
private float _lifetime;
|
|
[SerializeField]
|
|
private float _spawnSpeed = 0;
|
|
[SerializeField, Range(0, 1.001f)]
|
|
private float _spawnCounter = 0;
|
|
private WaveObserver _observer;
|
|
private float _initialSpawnSpeed;
|
|
private const float MAX_SPAWN_SPEED = 0.01f;
|
|
private const float RANDOM_MODIFIER = 5.0f;
|
|
private bool stopped = false;
|
|
|
|
|
|
public override void LevelStart()
|
|
{
|
|
_observer = WaveObserver.Instance;
|
|
_observer.Attach(this);
|
|
if (_spawnOnStart && _lifetime <= 0)
|
|
{
|
|
_prefab.Create(Position, parent: LevelManager.Instance.LevelTransform);
|
|
}
|
|
}
|
|
|
|
public override void LevelUpdate()
|
|
{
|
|
_lifetime += Time.deltaTime;
|
|
if (!stopped)
|
|
{
|
|
_spawnCounter += Time.deltaTime * _spawnSpeed;
|
|
}
|
|
if (_spawnCounter < 1) return;
|
|
|
|
_spawnCounter = 0;
|
|
_prefab.Create(Position, parent: LevelManager.Instance.LevelTransform);
|
|
_spawnSpeed = Mathf.Max(_initialSpawnSpeed / Random.Range(1.0f, RANDOM_MODIFIER), MAX_SPAWN_SPEED);
|
|
_observer.NotifySpawned(this);
|
|
}
|
|
public override bool Equals(ILevelObject other)
|
|
{
|
|
return other is SpawnerTile spawner
|
|
&& base.Equals(spawner)
|
|
&& spawner._prefab == _prefab
|
|
&& spawner._spawnSpeed == _spawnSpeed;
|
|
}
|
|
public override Dictionary<string, object> ToDictionary()
|
|
{
|
|
var dict = base.ToDictionary();
|
|
|
|
dict[nameof(_prefab)] = _prefab.name;
|
|
dict[nameof(_spawnSpeed)] = _spawnSpeed;
|
|
dict[nameof(_spawnCounter)] = _spawnCounter;
|
|
dict[nameof(_lifetime)] = _lifetime;
|
|
dict[nameof(_spawnOnStart)] = _spawnOnStart;
|
|
return dict;
|
|
}
|
|
|
|
internal void StopSpawn()
|
|
{
|
|
stopped = true;
|
|
}
|
|
|
|
internal void StartSpawn()
|
|
{
|
|
stopped = false;
|
|
}
|
|
|
|
|
|
public override void LoadDictionary(Dictionary<string, object> dict)
|
|
{
|
|
base.LoadDictionary(dict);
|
|
|
|
var prefabName = dict[nameof(_prefab)].ToString();
|
|
_prefab = Database.Instance.Prefabs[prefabName];
|
|
_spawnSpeed = dict[nameof(_spawnSpeed)].ToFloat();
|
|
_spawnCounter = dict[nameof(_spawnCounter)].ToFloat();
|
|
_lifetime = dict[nameof(_lifetime)].ToFloat();
|
|
_spawnOnStart = dict[nameof(_spawnOnStart)].ToBool();
|
|
}
|
|
|
|
public GameObject Prefab
|
|
{
|
|
set
|
|
{
|
|
_prefab = value;
|
|
}
|
|
get
|
|
{
|
|
return _prefab;
|
|
}
|
|
}
|
|
|
|
public void InitialSpawnSpeed(float value)
|
|
{
|
|
_initialSpawnSpeed = value;
|
|
_spawnSpeed = Mathf.Max(_initialSpawnSpeed / Random.Range(1.0f, RANDOM_MODIFIER - 2.0f), MAX_SPAWN_SPEED);
|
|
}
|
|
} |