miepzerino
2025-04-04 18e2f5b45ab0be301f0973b8cf6df714c2d05f7c
Assets/Scripts/Managers/GameManager.cs
@@ -1,20 +1,37 @@
using Assets.Scripts.Enums;
using Assets.Scripts.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Tilemaps;
public class GameManager : SettingsManager
{
    public static bool GameIsPaused = false;
    public GameObject damageTextPrefab;
    public GameObject healthTextPrefab;
    public GameObject lootTextPrefab;
    public Canvas playerUI;
    public Canvas pauseMenuUI;
    public Canvas worldSpaceUI;
    public GameObject levelChanger;
    public Tilemap tilemap;
    GenerateTileMap generateTileMap;
    [NonSerialized]
    public GenerateTileMap generateTileMap;
    [NonSerialized]
    public List<Vector3Int> destroyedTiles = new List<Vector3Int>();
    public GameObject pickups;
    public Tilemap fogTilemap;
    public FogOfWar fogOfWar;
    public GameObject backGroundPrefab;
    private void Awake()
    {
        GameIsPaused = false;
        SoundManager.instance.ChangeMusic(SoundName.MusicHappy);
        LoadTileMaps(SaveSystem.isGameLoaded);
    }
@@ -22,22 +39,65 @@
    private void LoadTileMaps(bool loadFromSave)
    {
        pauseMenuUI.GetComponent<PauseMenu>().Pause();
        levelChanger.GetComponent<Animator>().SetBool("SceneLoading", true);
        generateTileMap = tilemap.GetComponent<GenerateTileMap>();
        Debug.Log("waiting for async");
        StartCoroutine(generateTileMap.GenerateTiles(LoadTileMapsFinished));
        PauseGame();
        levelChanger.GetComponent<Animator>().SetBool("SceneLoading", true);
        if (loadFromSave)
        {
            LoadMapState();
        }
        Debug.Log("waiting for async map loading");
        StartCoroutine(generateTileMap.GenerateTiles(LoadTileMapsFinished, destroyedTiles));
    }
    private void InitializeBackgroundTiles()
    {
        GameObject tilesParent = new GameObject("BackgroundTiles");
        GameObject player = GameObject.FindGameObjectWithTag("Player");
        Vector3 backgroundPos = player.transform.position;
        // Adjust the new position based on whether y is positive or negative
        float colliderHeight = backGroundPrefab.GetComponent<BoxCollider2D>().size.y;
        if (backgroundPos.y >= 0)
        {
            backgroundPos.y -= Mathf.Abs(backgroundPos.y) % colliderHeight;
        }
        else
        {
            backgroundPos.y += Mathf.Abs(backgroundPos.y) % colliderHeight;
        }
        Instantiate(backGroundPrefab, (backgroundPos), Quaternion.identity, tilesParent.transform);
    }
    private void LoadMapState()
    {
        SaveDataMap mapState = SaveSystem.LoadMapState();
        if (mapState != null)
        {
            //fogOfWar.LoadFromSaveData(mapState.fogOfWarData);
            generateTileMap.SetSettingsFromSeed(mapState.seed);
            if (mapState.destroyedTiles != null && mapState.destroyedTiles.Count > 0)
            {
                // TODO rework load map (it's fucky wucky currently as I had to make an extra class for it to jsonify the tiles correctly, as unity does not like lists of arrays or 2d arrays)
                foreach (DestroyedTile tile in mapState.destroyedTiles)
                {
                    destroyedTiles.Add(tile.tileCoord.ConvertToVector3Int());
                }                //destroyedTiles.AddRange(mapState.destroyedTiles.Select(tile => { return tile.tileCoord; }).ToList().ConvertToVector3Int());
            }
        }
    }
    public void LoadTileMapsFinished()
    {
        Debug.Log("done async");
        Debug.Log("done async map loading");
        levelChanger.GetComponent<Animator>().SetBool("SceneLoading", false);
        //Initialize background tiles after the tilemap is loaded
        InitializeBackgroundTiles();
        GameLoaded();
    }
    public void GameLoaded()
    {
        pauseMenuUI.GetComponent<PauseMenu>().Resume();
        ResumeGame();
        pauseMenuUI.GetComponent<Animator>().SetTrigger("GameLoaded");
    }
@@ -79,6 +139,20 @@
        tmpText.text = healthRestored.ToString();
    }
    public void CharacterLootObtained(Vector3 position, Item itemReceived, int quantity)
    {
        // Offset the position slightly up so it doesn't spawn inside the ground/player
        position += Vector3.up * 0.5f;
        // Create text in world space (no parent needed)
        GameObject textObj = Instantiate(lootTextPrefab, position, Quaternion.identity, worldSpaceUI.transform);
        TextMeshProUGUI tmpText = textObj.GetComponent<TextMeshProUGUI>();
        tmpText.text = $"+{quantity} ({itemReceived.itemName})";
        // Ensure it's visible to the camera
        textObj.transform.rotation = Camera.main.transform.rotation;
    }
    public void CharacterDrill(ContactPoint2D contact, DrillDirection drillDirection)
    {
        GridLayout grid = tilemap.transform.GetComponentInParent<GridLayout>();
@@ -92,7 +166,10 @@
                cellCoord.x = cellCoord.x + 1;
                break;
            case DrillDirection.Down:
                cellCoord.y = cellCoord.y - 1;
                // Use player's center position for downward drilling
                Vector3 playerCenter = contact.rigidbody.transform.position;
                cellCoord = grid.WorldToCell(playerCenter);
                cellCoord.y = grid.WorldToCell(contact.point).y - 1; // Keep the vertical position from contact point
                break;
        }
@@ -100,13 +177,53 @@
        //Debug.Log(tilemap.HasTile(cellCoord));
        if (tilemap.HasTile(cellCoord))
        {
            tilemap.SetTile(cellCoord, null);
            Vector3 moveToPosition = grid.CellToWorld(cellCoord);
            moveToPosition.x += 0.5f;
            moveToPosition.y += 0.5f;
            CharacterEvents.characterDrillingToPosition.Invoke(moveToPosition);
            GameObject tileGameObject = tilemap.GetInstantiatedObject(cellCoord);
            if (tileGameObject?.GetComponent<Drillable>()?.isDrillable ?? false)
            {
                Vector3 cellWorldPosition = grid.CellToWorld(cellCoord);
                // middle of tile
                cellWorldPosition.x += 0.5f;
                cellWorldPosition.y += 0.5f;
                Dropable dropable = tileGameObject?.GetComponent<Dropable>();
                if (dropable?.isDropable ?? false)
                {
                    // Change no drops, only inventory
                    //Instantiate(tileGameObject?.GetComponent<Dropable>().dropable, cellWorldPosition, Quaternion.identity, pickups.transform);
                    Inventory playerInventory = contact.rigidbody.gameObject.GetComponent<Inventory>();
                    if (playerInventory != null)
                    {
                        Item item = dropable.dropable;
                        int dropAmount = dropable.GetRandomDropAmount();
                        playerInventory.AddItem(item, dropAmount);
                        CharacterLootObtained(tileGameObject.transform.position, item, dropAmount);
                    }
                }
                tilemap.SetTile(cellCoord, null);
                destroyedTiles.Add(cellCoord);
                CharacterEvents.characterDrillingToPosition.Invoke(cellWorldPosition, drillDirection);
            }
            else
            {
                //CharacterEvents.characterDrillingToPositionAbort.Invoke(moveToPosition);
            }
        }
    }
    #endregion
    #region GameState
    public static void PauseGame()
    {
        Time.timeScale = 0f;
        GameIsPaused = true;
        //GameStateEvents.gameStatePauseChanged.Invoke(GameIsPaused);
    }
    public static void ResumeGame()
    {
        Time.timeScale = 1f;
        GameIsPaused = false;
        //GameStateEvents.gameStatePauseChanged.Invoke(GameIsPaused);
    }
    #endregion
}