Untitled

mail@pastecode.io avatar
unknown
csharp
22 days ago
8.0 kB
9
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using Unity.Cinemachine;
using UnityEngine;
using UnityEngine.UI;

public class ObjectActivator : MonoBehaviour {
    public Button activationButton;
    public GameObject smokeEffectPrefab;

    private List<GameObject> objectList = new List<GameObject>();
    private int clickCount = 0;

    public SavingSystem savingSystem;
    private GameData gameData;

    //  animación
    public float animationDuration = 1.0f;  
    public float yOffset = 50f;            
    public AnimationCurve animationCurve;   

   
    public CinemachineCamera freeLookCamera;  
    public float targetZoom = 30f;             
    public float zoomRestoreDelay = 4f;         
    private float originalZoom;                
    private Coroutine restoreZoomCoroutine;
    public float zoomSmoothTime = 1f;


    void Start() {
       
        savingSystem = Object.FindFirstObjectByType<SavingSystem>();

       
        if (freeLookCamera != null) {
            originalZoom = freeLookCamera.Lens.FieldOfView;  
        }


        if (savingSystem == null) {
            Debug.LogError("No se encontró el componente SavingSystem.");
            return;
        }

       
        LoadGameData();

        
        if (gameData != null) {
            gameData.objectActivatorData.currentClicksRequired = gameData.objectActivatorData.currentClicksRequired > 0 ? gameData.objectActivatorData.currentClicksRequired : 3;
        }

       
        FindObjectsWithPrefix();
        SortObjectsBySuffix();
        DeactivateAllObjects();

        if (activationButton != null) {
            activationButton.onClick.AddListener(OnButtonClicked);
        }

      
        ActivateSavedObjects();
    }



    void FindObjectsWithPrefix() {
        objectList.Clear();
        GameObject[] allObjects = Object.FindObjectsByType<GameObject>(FindObjectsSortMode.None);

        foreach (GameObject obj in allObjects) {
            if (obj.name.StartsWith("GJR.")) {
                objectList.Add(obj);
            }
        }
    }

    void SortObjectsBySuffix() {
        objectList.Sort((a, b) => {
            int suffixA = int.Parse(a.name.Substring(4));  // asumiendo gjr. tiene 4 caracteres maaximo
            int suffixB = int.Parse(b.name.Substring(4));
            return suffixA.CompareTo(suffixB);
        });
    }

    void DeactivateAllObjects() {
        foreach (GameObject obj in objectList) {
            obj.SetActive(false);
        }
    }

    void OnButtonClicked() {
        clickCount++;

        if (clickCount >= gameData.objectActivatorData.currentClicksRequired && gameData.objectActivatorData.currentIndex < objectList.Count) {
            GameObject objectToActivate = objectList[gameData.objectActivatorData.currentIndex];

            // inicio laa activacion 
            StartCoroutine(ActivateObjectWithAnimation(objectToActivate));

            string objName = objectToActivate.name;
            if (!gameData.objectActivatorData.activatedObjects.Contains(objName)) {
                gameData.objectActivatorData.activatedObjects.Add(objName);
            }

            gameData.objectActivatorData.currentIndex++;
            clickCount = 0;

            if (freeLookCamera != null) {
                AdjustCameraZoom();
            }
        }
    }

    void AdjustCameraZoom() {
        
        if (restoreZoomCoroutine != null) {
            StopCoroutine(restoreZoomCoroutine);
        }

      
        StartCoroutine(SmoothZoom(targetZoom));

       
        restoreZoomCoroutine = StartCoroutine(RestoreZoomAfterDelay());
    }

    IEnumerator SmoothZoom(float targetFOV) {
        float startFOV = freeLookCamera.Lens.FieldOfView;
        float elapsedTime = 0f;

        while (elapsedTime < zoomSmoothTime) {
            elapsedTime += Time.deltaTime;
            freeLookCamera.Lens.FieldOfView = Mathf.Lerp(startFOV, targetFOV, elapsedTime / zoomSmoothTime);
            yield return null;
        }

        freeLookCamera.Lens.FieldOfView = targetFOV;  
    }

    IEnumerator RestoreZoomAfterDelay() {
      
        yield return new WaitForSeconds(zoomRestoreDelay);

    
        StartCoroutine(SmoothZoom(originalZoom));
    }

    IEnumerator ActivateObjectWithAnimation(GameObject obj) {
        // guardoooooo la posición original
        Vector3 originalPosition = obj.transform.position;
        Vector3 startPosition = originalPosition + new Vector3(0, yOffset, 0);  

     
        obj.SetActive(true);

    
        Renderer objectRenderer = obj.GetComponent<Renderer>();
        if (objectRenderer == null) {
            Debug.LogWarning("El objeto no tiene un componente Renderer.");
            yield break;
        }

        Material objectMaterial = objectRenderer.material;

        // inicializo alpha en 0
        Color objectColor = objectMaterial.color;
        objectColor.a = 0f;
        objectMaterial.color = objectColor;

        float elapsedTime = 0f;
        float smokeTriggerTime = animationDuration * 0.8f;  // 80% de la animación completada antes de lanzar el humo

        bool smokeTriggered = false;

        while (elapsedTime < animationDuration) {
          
            elapsedTime += Time.deltaTime;
            float t = elapsedTime / animationDuration;
            t = animationCurve.Evaluate(t);  // Aplicar la curva de animación

           
            obj.transform.position = Vector3.Lerp(startPosition, originalPosition, t);

           
            objectColor.a = Mathf.Lerp(0f, 1f, t);  // De transparente a opaco
            objectMaterial.color = objectColor;

            // activo le humo antes del llegar al final
            if (!smokeTriggered && elapsedTime >= smokeTriggerTime) {
                smokeTriggered = true;
                TriggerSmokeEffect(originalPosition);
            }

            yield return null;
        }

        // objeto en en su posición final y completamente opaco
        obj.transform.position = originalPosition;
        objectColor.a = 1f;
        objectMaterial.color = objectColor;
    }



    void TriggerSmokeEffect(Vector3 position) {
        if (smokeEffectPrefab != null) {
           
            Quaternion rotation = Quaternion.Euler(-100, 0, 0); 

          
            GameObject smokeEffect = Instantiate(smokeEffectPrefab, position, rotation);

          
            Destroy(smokeEffect, 2f);  
        }
    }



    void ActivateSavedObjects() {
        if (gameData != null && gameData.objectActivatorData.activatedObjects != null) {
            foreach (string objName in gameData.objectActivatorData.activatedObjects) {
                foreach (GameObject obj in objectList) {
                    if (obj.name == objName) {
                        obj.SetActive(true);
                        break;
                    }
                }
            }
        } else {
            Debug.LogWarning("null, no se pueden activar los objetos guardados.");
        }
    }

    
    public ObjectActivatorData GetObjectActivatorData() {
        return gameData.objectActivatorData;
    }

    void LoadGameData() {
        
        gameData = savingSystem.LoadGameData();

      
        if (gameData == null || gameData.objectActivatorData == null) {
            Debug.LogWarning("GameData u objectativator null asi que nicializando nuevos datos.");
            gameData = new GameData();  // Inicializar datos si no existen
        }

       
        if (gameData.objectActivatorData.activatedObjects == null) {
            Debug.LogWarning("inicializando lista vacía.");
            gameData.objectActivatorData.activatedObjects = new List<string>();
        }

        
        Debug.Log("Datos Objects cargados");
    }
}
Leave a Comment