BlockGenerator.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using UnityEngine;
  2. namespace Generator
  3. {
  4. public class BlockGenerator : MonoBehaviour
  5. {
  6. [SerializeField] private PathMaker _pathMaker;
  7. [SerializeField] private ColumnMaker _columnMaker;
  8. [SerializeField] private GameObject _blockPrefab;
  9. [SerializeField] private GameObject _extendedBlockPrefab;
  10. private void SpawnBlock(Vector2 position, int gravityDirection, GameObject prefab)
  11. {
  12. var block = Instantiate(prefab);
  13. block.transform.position = new Vector2(position.x, position.y - gravityDirection);
  14. var scale = block.transform.localScale;
  15. block.transform.localScale = new Vector3(scale.x, scale.y * gravityDirection, scale.z);
  16. }
  17. private void CreateNewColumn(Vector2Int[] positions, int gravityDirection)
  18. {
  19. var position = positions[0];
  20. if (gravityDirection > 0)
  21. {
  22. foreach (var givenPosition in positions)
  23. {
  24. if (givenPosition.y < position.y)
  25. position = givenPosition;
  26. }
  27. }
  28. else
  29. {
  30. foreach (var givenPosition in positions)
  31. {
  32. if (givenPosition.y > position.y)
  33. position = givenPosition;
  34. }
  35. }
  36. SpawnBlock(position, gravityDirection, _blockPrefab);
  37. }
  38. private void CreateBlock(Vector2 position, int gravityDirection, bool extended) =>
  39. SpawnBlock(position, gravityDirection, extended ? _extendedBlockPrefab : _blockPrefab);
  40. private void Awake()
  41. {
  42. _columnMaker.OnCreateColumn += CreateNewColumn;
  43. _pathMaker.OnCreateBlock += CreateBlock;
  44. }
  45. private void OnDestroy()
  46. {
  47. _columnMaker.OnCreateColumn -= CreateNewColumn;
  48. _pathMaker.OnCreateBlock -= CreateBlock;
  49. }
  50. }
  51. }