Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

Quiero que si el usuario empieza el click en un elemento de la UI no se haga el perform…

  1. User

    Quiero que si el usuario empieza el click en un elemento de la UI no se haga el perform selection

    using System; using System.Collections.Generic; using System.Linq; using Game.Systems; using Game.Systems.Buildings; using Unity.Mathematics; using UnityEngine; using UnityEngine.Serialization;

    namespace Game.ImprovedAI { public class MouseSelectionBox : MonoBehaviour { [SerializeField] private float minDragDistance = 0.1f; [SerializeField] private LayerMask unitLayerMask; [SerializeField] private LayerMask terrainLayerMask; [SerializeField] private LayerMask buildingLayerMask; [SerializeField] private float offsetBetweenSoldiers = 1;

        private bool isSelecting = false;
        private bool isDragging = false;
        private Vector3 mousePosition1;
        private Vector3 selectionCenter; // For Gizmos
        private Vector3 selectionHalfExtents;
        private Vector3 worldPos1;
        private Vector3 worldPos2;
        private Vector3 worldPos3;
        private Vector3 worldPos4;
        private Vector3 center;
        private Vector3 size;// For Gizmos
        private BuildingBase currentBuilding;
        private bool isDay = true;
        private bool isActive = false;
        
        private float clickTime = 0.3f; // Tiempo en segundos para detectar doble click
        private float elapsedTime = 0.0f;
        private int clickCount = 0;
        
        public List<UnitBase> selectedUnits = new List<UnitBase>();
    
        public void Init()
        {
            GameManager.Instance.OnDayStart += StartDay;
            GameManager.Instance.OnNightStart += StartNight;
            GameManager.Instance.OnEveningStart += StartNight;
            isActive = true;
        }
    
        private void Update()
        {
            if(!isActive) return;
            
            if (GameManager.Instance.DeckController.handController.IsDragging 
                || GameManager.Instance.VillagersPlacer.dragging)
            {
                ResetSelection();
                return;
            }
    
            HandleMousePosition();
        }
    
        private void HandleMousePosition()
        {
            SelectBuilding();
    
            //This deselects units and checks double click
            if (Input.GetMouseButtonDown(0))
            {
                isSelecting = true;
                isDragging = false; // Reset the dragging flag
                mousePosition1 = Input.mousePosition;
                DeselectUnits(); 
                
                clickCount++;
                
                if (clickCount == 1)
                {
                    elapsedTime = Time.unscaledTime;
                }
                else if (clickCount == 2)
                {
                    if ((Time.unscaledTime - elapsedTime) < clickTime)
                    {
                        SelectAllUnitOfType();
                    }
                    ResetClick();
                }
            }
            // This moves units
            else if (selectedUnits.Count > 0 && Input.GetMouseButtonDown(1))
            {
                MoveUnits();
            }
            
            // This selects one unit
            if ((Time.unscaledTime - elapsedTime) > clickTime)
            {
                if (clickCount == 1)
                {
                    SelectOneUnit();
                }
                ResetClick();
            }
    
    
            //This says if we are dragging and disables panels in buildings
            if (isSelecting && (Input.mousePosition - mousePosition1).magnitude > minDragDistance)
            {
                isDragging = true;
    
                //If dragging disable panel
                if (currentBuilding != null)
                {
                    var placerHelper = currentBuilding.transform.GetComponent<PlacerHelper>();
                    placerHelper.EnableOutline(false);
                    GameManager.Instance.BuildingPanelManager.DisableAllPanels();
                }
            }
    
            // This selects several units
            if (Input.GetMouseButtonUp(0))
            {
                isSelecting = false;
    
                if (isDragging)
                {
                    PerformSelection();
                    isDragging = false; // Reset the dragging flag
                }
            }
        }
    
        private void SelectOneUnit()
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, unitLayerMask))
            {
                UnitBase unitBase = hit.transform.gameObject.GetComponent<UnitBase>();
                if (unitBase != null)
                {
                    unitBase.EnableHighlight(true);
                    if (!selectedUnits.Contains(unitBase)) selectedUnits.Add(unitBase);
                }
            }
        }
    
        private void SelectAllUnitOfType()
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, unitLayerMask))
            {
                UnitBase unitBase = hit.transform.gameObject.GetComponent<UnitBase>();
                if (unitBase != null)
                {
                    var soldiers = GameManager.Instance.VillagerTracker.GetAliveSoldiersOfType(unitBase);
                    
                    selectedUnits.Clear();
                    selectedUnits.AddRange(soldiers);
    
                    foreach (var soldier in selectedUnits)
                    {
                        soldier.EnableHighlight(true);
                    }
                }
            }
            
        }
    
        private void SelectBuilding()
        {
            if (Input.GetMouseButtonDown(0) && !isDragging)
            {
                if (currentBuilding != null)
                {
                    var placerHelper = currentBuilding.transform.GetComponent<PlacerHelper>();
                    placerHelper.EnableOutline(false);
                }
    
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit, Mathf.Infinity, buildingLayerMask) && isDay)
                {
                    if (currentBuilding != null)
                    {
                        currentBuilding.showingPanel = false;
                    }
    
                    currentBuilding = hit.transform.GetComponentInParent<BuildingBase>();
                    if (currentBuilding.IsBuilded && !currentBuilding.IsDestroyed && currentBuilding.CanStartPanel)
                    {
                        hit.transform.GetComponentInParent<PlacerHelper>().EnableOutline(true);
                        currentBuilding.InitPanel();
                    }
                }
            }
        }
    
        private void ResetSelection()
        {
            isSelecting = false;
            isDragging = false;
        }
        
        void DeselectUnits()
        {
            if (selectedUnits.Count > 0)
            {
                foreach (var unit in selectedUnits)
                {
                    unit.EnableHighlight(false);
                }
    
                selectedUnits.Clear();
            }
        }
    
        public void EnableSelector(bool enabled)
        {
            isActive = enabled;
    
            if (!enabled)
            {
                isDragging = false;
            }
        }
    
        private void MoveUnits()
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, terrainLayerMask))
            {
                Vector3 hitPoint = hit.point;
                CalculateFormation(hitPoint);
            }
        }
        
        void ResetClick()
        {
            clickCount = 0;
            elapsedTime = 0.0f;
        }
    
        private void OnGUI()
        {
            // Draw the selection rectangle if the user is dragging the mouse
            if (isDragging)
            {
                Rect rect = GetScreenRect(mousePosition1, Input.mousePosition);
                DrawScreenRect(rect, new Color(0.8f, 0.8f, 0.95f, 0.25f)); // Tint color and alpha
                DrawScreenRectBorder(rect, 2, Color.white);
            }
        }
    
        // Utility function to create a rectangle
        public static Rect GetScreenRect(Vector3 screenPosition1, Vector3 screenPosition2)
        {
            // Move origin from bottom left to top left
            screenPosition1.y = Screen.height - screenPosition1.y;
            screenPosition2.y = Screen.height - screenPosition2.y;
            // Calculate corners
            var topLeft = Vector3.Min(screenPosition1, screenPosition2);
            var bottomRight = Vector3.Max(screenPosition1, screenPosition2);
            // Create the rect
            return Rect.MinMaxRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
        }
    
        // Utility function to draw a rectangle on the screen
        public static void DrawScreenRect(Rect rect, Color color)
        {
            GUI.color = color;
            GUI.DrawTexture(rect, Texture2D.whiteTexture);
        }
    
        // Utility function to draw a border around the rectangle
        public static void DrawScreenRectBorder(Rect rect, float thickness, Color color)
        {
            // Top
            DrawScreenRect(new Rect(rect.xMin, rect.yMin, rect.width, thickness), color);
            // Left
            DrawScreenRect(new Rect(rect.xMin, rect.yMin, thickness, rect.height), color);
            // Right
            DrawScreenRect(new Rect(rect.xMax - thickness, rect.yMin, thickness, rect.height), color);
            // Bottom
            DrawScreenRect(new Rect(rect.xMin, rect.yMax - thickness, rect.width, thickness), color);
        }
    
        // Placeholder for detecting selected objects within the rectangle
        // This needs to be defined based on your specific needs
        
        private void PerformSelection()
        {
            if (!isDragging) return;
    
            // Define your fixed distance from the camera
            float fixedDistance = 100.0f;
    
            // Get the rect and the two points representing opposite corners
            Rect selectionRect = GetScreenRect(mousePosition1, Input.mousePosition);
            Vector3 screenPos1 = new Vector3(selectionRect.xMin, Screen.height - selectionRect.yMin, Camera.main.nearClipPlane);
            Vector3 screenPos2 = new Vector3(selectionRect.xMax, Screen.height - selectionRect.yMax, Camera.main.nearClipPlane);
            Vector3 screenPos3 = new Vector3(selectionRect.xMin, Screen.height - selectionRect.yMax, Camera.main.nearClipPlane);
            Vector3 screenPos4 = new Vector3(selectionRect.xMax, Screen.height - selectionRect.yMin, Camera.main.nearClipPlane);
    
            // Convert the corners of the rectangle from screen space to world space at a fixed distance
            worldPos1 = Camera.main.ScreenToWorldPoint(screenPos1);
            worldPos2 = Camera.main.ScreenToWorldPoint(screenPos2);
            worldPos3 = Camera.main.ScreenToWorldPoint(screenPos3);
            worldPos4 = Camera.main.ScreenToWorldPoint(screenPos4);
    
            // Calculate the center and size of the box in world space
            center = (worldPos1 + worldPos2) / 2f;
            size = new Vector3(Vector3.Distance(worldPos1, worldPos4), Vector3.Distance(worldPos1, worldPos3), 0);
            
    
            // Optionally, visualize the box for debugging (comment out for production code)
            Debug.DrawLine(worldPos1, worldPos2, Color.green, 2f);
    
            // Perform the box cast
            RaycastHit[] hitObjects = Physics.BoxCastAll(center, size / 2f, Camera.main.transform.forward, Camera.main.transform.rotation, fixedDistance, unitLayerMask);
            foreach (RaycastHit hit in hitObjects)
            {
                UnitBase unitBase = hit.transform.gameObject.GetComponent<UnitBase>();
                if (unitBase != null)
                {
                    unitBase.EnableHighlight(true);
                    if(!selectedUnits.Contains(unitBase)) selectedUnits.Add(unitBase);
                }
            }
        }
    
        public void CalculateFormation(Vector3 targetPosition)
        {
            int totalUnits = selectedUnits.Count; // Include the commander in the formation count
            int sideLength = Mathf.CeilToInt(Mathf.Sqrt(totalUnits)); // Calculate the side length of the formation square
            int soldierCount = 0;
    
            // Find the center of the formation grid
            int centerIndex = sideLength / 2;
    
            //Ordenar selected units, primero las front y despues las behind
            selectedUnits = selectedUnits.OrderBy(x => x.UnitPositionType).ToList();
    
            // Calculate the offset between each soldier
            
            for (int x = 0; x < sideLength; x++)
            {
                for (int z = 0; z < sideLength; z++)
                {
                    
                    if (soldierCount >= selectedUnits.Count)
                        break; // We’ve positioned all the soldiers
    
                    // Calculate the position for each soldier relative to the center
                    Vector3 offsetToCenter = new Vector3(
                        (x - centerIndex) * offsetBetweenSoldiers,
                        0,
                        (z - centerIndex) * offsetBetweenSoldiers
                    );
    
                    // if (selectedUnits[soldierCount].UnitPositionType == UnitBase.UnitPosition.Behind)
                    // {
                    //     offsetToCenter += new Vector3(0, 0, -2);
                    // }
    
                    Vector3 soldierPosition = targetPosition + offsetToCenter;
            
                    // Move soldier to the computed position
                    selectedUnits[soldierCount].MoveTo(soldierPosition, true);
                    bool isBehind = selectedUnits[soldierCount].UnitPositionType == UnitBase.UnitPosition.Behind;
                    soldierCount++;
                }
            }
        }
        
        private void StartNight(object sender, EventArgs e)
        {
            isDay = false;
        }
    
        private void StartDay(object sender, EventArgs e)
        {
            isDay = true;
        }
        
        private void OnDestroy()
        {
            GameManager.Instance.OnDayStart -= StartDay;
            GameManager.Instance.OnNightStart -= StartNight;
        }
       
    }
    

    }

  2. Assistant

    Para asegurarte de que no se realice la selección si el usuario comienza el clic en un elemento de la UI, necesitas verificar si el clic inicial ocurrió sobre un elemento de la UI antes de proceder con cualquier lógica de selección. En Unity, puedes utilizar el método EventSystem.current.IsPointerOverGameObject() para determinar si el puntero está sobre un elemento de UI en el momento del clic.

    Aquí tienes cómo puedes integrar esta verificación en tu código MouseSelectionBox:

    1. Asegúrate de tener la referencia al EventSystem en tu escena, lo cual generalmente ya está presente si estás usando el sistema de UI de Unity.
    2. Antes de realizar cualquier operación relacionada con la selección, utiliza IsPointerOverGameObject() para comprobar si el puntero está sobre un elemento de UI.

    Aquí hay un ejemplo de cómo modificar el método HandleMousePosition para incluir esta verificación:

    using UnityEngine.EventSystems;
    
    // ... (El resto del código permanece igual)
    
    private void HandleMousePosition()
    {
        // Comprobar si el clic comenzó sobre un elemento de UI
        if (EventSystem.current.IsPointerOverGameObject())
        {
            return; // Si el puntero está sobre la UI, no procedas con la selección.
        }
    
        SelectBuilding();
    
        // Esta parte deselecciona unidades y comprueba el doble clic
        if (Input.GetMouseButtonDown(0))
        {
            isSelecting = true;
            isDragging = false; // Restablecer la bandera de arrastre
            mousePosition1 = Input.mousePosition;
            DeselectUnits(); 
            
            clickCount++;
            
            if (clickCount == 1)
            {
                elapsedTime = Time.unscaledTime;
            }
            else if (clickCount == 2)
            {
                if ((Time.unscaledTime - elapsedTime) < clickTime)
                {
                    SelectAllUnitOfType();
                }
                ResetClick();
            }
        }
        // Este mueve las unidades
        else if (selectedUnits.Count > 0 && Input.GetMouseButtonDown(1))
        {
            MoveUnits();
        }
        
        // Este selecciona una unidad
        if ((Time.unscaledTime - elapsedTime) > clickTime)
        {
            if (clickCount == 1)
            {
                SelectOneUnit();
            }
            ResetClick();
        }
    
        // Este detecta si estamos arrastrando y deshabilita paneles en los edificios
        if (isSelecting && (Input.mousePosition - mousePosition1).magnitude > minDragDistance)
        {
            isDragging = true;
    
            // Si estamos arrastrando, deshabilitar el panel
            if (currentBuilding != null)
            {
                var placerHelper = currentBuilding.transform.GetComponent<PlacerHelper>();
                placerHelper.EnableOutline(false);
                GameManager.Instance.BuildingPanelManager.DisableAllPanels();
            }
        }
    
        // Este selecciona varias unidades
        if (Input.GetMouseButtonUp(0))
        {
            isSelecting = false;
    
            if (isDragging)
            {
                PerformSelection();
                isDragging = false; // Restablecer la bandera de arrastre
            }
        }
    }
    

    Este cambio asegura que cualquier intento de clic o selección que comience encima de un elemento de la UI sea ignorado, manteniendo la lógica de selección centrada solo en la jugabilidad y reduciendo interferencias no deseadas por los elementos de UI.

  3. User

    Pero si el click ya habia empezado y el release termina en un elemento de UI no lo ignore

  4. Assistant

    Para manejar el caso en el que el clic se inicia fuera de un elemento de UI, pero finaliza sobre un elemento de UI, querrás asegurarte de que el inicio del clic se realiza en un área jugable, pero permitir que el evento de liberación del clic ocurra donde sea, incluyendo la UI.

    Una manera de lograr esto es solo verificar EventSystem.current.IsPointerOverGameObject() cuando el clic comienza. Si el clic comienza sobre un elemento de UI, simplemente no inicies ninguna operación de selección.

    Aquí tienes cómo puedes manejar esto manteniendo la verificación solo al inicio del clic:

    using UnityEngine.EventSystems;
    
    // ... (El resto del código permanece igual)
    
    private void HandleMousePosition()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (EventSystem.current.IsPointerOverGameObject())
            {
                isSelecting = false; // No iniciar la selección si se empieza sobre un elemento de UI
                return;
            }
            
            isSelecting = true;
            isDragging = false; // Reset the dragging flag
            mousePosition1 = Input.mousePosition;
            DeselectUnits(); 
            
            clickCount++;
            
            if (clickCount == 1)
            {
                elapsedTime = Time.unscaledTime;
            }
            else if (clickCount == 2)
            {
                if ((Time.unscaledTime - elapsedTime) < clickTime)
                {
                    SelectAllUnitOfType();
                }
                ResetClick();
            }
        }
        // Este mueve las unidades
        else if (selectedUnits.Count > 0 && Input.GetMouseButtonDown(1))
        {
            MoveUnits();
        }
        
        // Este selecciona una unidad
        if ((Time.unscaledTime - elapsedTime) > clickTime)
        {
            if (clickCount == 1)
            {
                SelectOneUnit();
            }
            ResetClick();
        }
    
        // Este detecta si estamos arrastrando y deshabilita paneles en los edificios
        if (isSelecting && (Input.mousePosition - mousePosition1).magnitude > minDragDistance)
        {
            isDragging = true;
    
            // Si estamos arrastrando, deshabilitar el panel
            if (currentBuilding != null)
            {
                var placerHelper = currentBuilding.transform.GetComponent<PlacerHelper>();
                placerHelper.EnableOutline(false);
                GameManager.Instance.BuildingPanelManager.DisableAllPanels();
            }
        }
    
        // Este selecciona varias unidades
        if (Input.GetMouseButtonUp(0))
        {
            isSelecting = false;
    
            if (isDragging)
            {
                PerformSelection();
                isDragging = false; // Reset the dragging flag
            }
        }
    }
    
    

    Con este enfoque, solo ignoras el evento de clic si comienza sobre un elemento de UI. Si el clic comienza sobre el juego, puedes llevar a cabo la selección o cualquier otra operación independientemente de dónde termine el clic. Esto permite que las interacciones que se inician válidamente sobre la escena de juego continúen, incluso si se finalizan en la UI.