maus234

SearchZone

Apr 14th, 2024
781
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.82 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5.  
  6. public class SearchZone : MonoBehaviour
  7. {
  8.     private BoxCollider2D boxCollider;
  9.     public List<Collider2D> detectedCollidersTree = new List<Collider2D>();
  10.     public List<Collider2D> detectedCollidersWall = new List<Collider2D>();
  11.     private bool isSafeZoneDetected = false;
  12.  
  13.     // References to GameObjects representing the corners of the collider
  14.     public GameObject topLeftCorner;
  15.     public GameObject topRightCorner;
  16.     public GameObject bottomLeftCorner;
  17.     public GameObject bottomRightCorner;
  18.  
  19.     private float checkInterval = 1f; // Time interval between checks
  20.     private int requiredTreeCount = 5;
  21.     private float expansionStep = 0.5f;
  22.  
  23.     void Start()
  24.     {
  25.         boxCollider = GetComponent<BoxCollider2D>() ?? gameObject.AddComponent<BoxCollider2D>();
  26.         boxCollider.isTrigger = true;
  27.         DontDestroyOnLoad(gameObject);
  28.  
  29.         // Initialize corner GameObjects
  30.         InitializeCorners();
  31.  
  32.         StartCoroutine(AdjustColliderRoutine());
  33.     }
  34.  
  35.     private void InitializeCorners()
  36.     {
  37.         // Instantiate corner GameObjects or assign them if they are already in the scene
  38.         topLeftCorner = new GameObject("TopLeftCorner");
  39.         topRightCorner = new GameObject("TopRightCorner");
  40.         bottomLeftCorner = new GameObject("BottomLeftCorner");
  41.         bottomRightCorner = new GameObject("BottomRightCorner");
  42.  
  43.         // Initially set the corner positions based on the collider's current bounds
  44.         SetCornerPositions();
  45.     }
  46.  
  47.     private void SetCornerPositions()
  48.     {
  49.         Physics2D.SyncTransforms();
  50.  
  51.         Vector3 topRight = new Vector3(boxCollider.bounds.max.x, boxCollider.bounds.max.y, 0);
  52.         Vector3 topLeft = new Vector3(boxCollider.bounds.min.x, boxCollider.bounds.max.y, 0);
  53.         Vector3 bomottRight = new Vector3(boxCollider.bounds.max.x, boxCollider.bounds.min.y, 0);
  54.         Vector3 bottomLeft = new Vector3(boxCollider.bounds.min.x, boxCollider.bounds.min.y, 0);
  55.  
  56.         topLeftCorner.transform.parent = this.transform;
  57.         topRightCorner.transform.parent = this.transform;
  58.         bottomLeftCorner.transform.parent = this.transform;
  59.         bottomRightCorner.transform.parent = this.transform;
  60.     }
  61.  
  62.     private void UpdateCornerPositions()
  63.     {
  64.         // Recalculates the positions of the corner GameObjects after the collider has been resized or moved
  65.         Vector2 offset = boxCollider.offset;
  66.         Vector2 size = boxCollider.size;
  67.         Vector3 centerPosition = transform.position + new Vector3(offset.x, offset.y, 0);
  68.  
  69.         topLeftCorner.transform.position = centerPosition + new Vector3(-size.x / 2, size.y / 2, 0);
  70.         topRightCorner.transform.position = centerPosition + new Vector3(size.x / 2, size.y / 2, 0);
  71.         bottomLeftCorner.transform.position = centerPosition + new Vector3(-size.x / 2, -size.y / 2, 0);
  72.         bottomRightCorner.transform.position = centerPosition + new Vector3(size.x / 2, -size.y / 2, 0);
  73.     }
  74.  
  75.     IEnumerator AdjustColliderRoutine()
  76.     {
  77.         // Coroutine to periodically check and adjust the size and position of the collider
  78.         while (true)
  79.         {
  80.             if (ShouldExpand())
  81.             {
  82.                 yield return StartCoroutine(ExpandZone());
  83.             }
  84.  
  85.             AdjustForNewObstacles();
  86.  
  87.             yield return new WaitForSeconds(checkInterval);
  88.         }
  89.     }
  90.  
  91.     private IEnumerator ExpandZone()
  92.     {
  93.         // Coroutine to handle the expansion of the collider
  94.         while (detectedCollidersTree.Count < requiredTreeCount && !isSafeZoneDetected)
  95.         {
  96.             boxCollider.size += new Vector2(expansionStep, 0);
  97.             UpdateCornerPositions(); // Update the corner positions
  98.  
  99.             if (!IsWallOnRightSide())
  100.             {
  101.                 boxCollider.offset += new Vector2(expansionStep / 2, 0);
  102.                 UpdateCornerPositions(); // Update the corner positions
  103.             }
  104.  
  105.             yield return new WaitForFixedUpdate();
  106.  
  107.             if (IsWallOnRightSide())
  108.             {
  109.                 AdjustColliderToWall();
  110.                 break;
  111.             }
  112.         }
  113.     }
  114.  
  115.     private bool ShouldExpand()
  116.     {
  117.         // Determines if the collider should expand based on the number of detected tree colliders and safe zone status
  118.         return detectedCollidersTree.Count < requiredTreeCount && !isSafeZoneDetected;
  119.     }
  120.  
  121.     private void AdjustForNewObstacles()
  122.     {
  123.         // Adjusts the collider in response to newly detected walls
  124.         if (detectedCollidersWall.Count > 0)
  125.         {
  126.             var rightmostWall = GetRightmostWall();
  127.             if (rightmostWall != null)
  128.             {
  129.                 AdjustCollider(rightmostWall);
  130.             }
  131.         }
  132.     }
  133.  
  134.     private Collider2D GetRightmostWall()
  135.     {
  136.         // Returns the rightmost wall detected by sorting walls based on their x position
  137.         return detectedCollidersWall.OrderByDescending(wall => wall.transform.position.x).FirstOrDefault();
  138.     }
  139.  
  140.     private bool IsWallOnRightSide()
  141.     {
  142.         // Check if any detected walls are located to the right of the collider's current right boundary
  143.         return detectedCollidersWall.Any(wall => wall.transform.position.x > boxCollider.bounds.max.x);
  144.     }
  145.  
  146.     private void AdjustColliderToWall()
  147.     {
  148.         // Adjust the width of the collider so it does not extend beyond a detected wall on the right
  149.         Collider2D rightmostWallInsideBounds = detectedCollidersWall.OrderByDescending(wall => wall.transform.position.x).FirstOrDefault();
  150.         if (rightmostWallInsideBounds != null)
  151.         {
  152.             float wallPositionX = rightmostWallInsideBounds.transform.position.x;
  153.             float colliderRightBoundary = boxCollider.bounds.max.x;
  154.             if (wallPositionX < colliderRightBoundary)
  155.             {
  156.                 float newWidth = wallPositionX - boxCollider.bounds.min.x;
  157.                 boxCollider.size = new Vector2(newWidth, boxCollider.size.y);
  158.                 UpdateCornerPositions(); // Update the corner positions
  159.             }
  160.         }
  161.     }
  162.  
  163.     private void AdjustCollider(Collider2D rightmostWall)
  164.     {
  165.         // Adjusts the width of the collider to match the position of the rightmost detected wall
  166.         Physics2D.SyncTransforms();
  167.         Physics2D.SyncTransforms();
  168.         float wallPositionX = rightmostWall.transform.position.x;
  169.         float colliderLeftBoundary = transform.position.x + boxCollider.offset.x - boxCollider.size.x / 2;
  170.  
  171.         if (wallPositionX > colliderLeftBoundary)
  172.         {
  173.             float newWidth = wallPositionX - colliderLeftBoundary;
  174.             boxCollider.size = new Vector2(newWidth, boxCollider.size.y);
  175.             UpdateCornerPositions(); // Update the corner positions
  176.             Physics2D.SyncTransforms();
  177.         }
  178.     }
  179.  
  180.     private void OnTriggerEnter2D(Collider2D collision)
  181.     {
  182.         // Trigger detection for trees, walls, and safe zones
  183.         if (collision.CompareTag("Tree"))
  184.         {
  185.             detectedCollidersTree.Add(collision);
  186.         }
  187.         else if (collision.CompareTag("Wall"))
  188.         {
  189.             detectedCollidersWall.Add(collision);
  190.         }
  191.         else if (collision.CompareTag("SafeZone"))
  192.         {
  193.             isSafeZoneDetected = true;
  194.         }
  195.     }
  196.  
  197.     private void OnTriggerExit2D(Collider2D collision)
  198.     {
  199.         // Handle objects exiting the trigger zone
  200.         if (collision.CompareTag("Tree"))
  201.         {
  202.             detectedCollidersTree.Remove(collision);
  203.         }
  204.         else if (collision.CompareTag("Wall"))
  205.         {
  206.             detectedCollidersWall.Remove(collision);
  207.         }
  208.         else if (collision.CompareTag("SafeZone"))
  209.         {
  210.             isSafeZoneDetected = false;
  211.         }
  212.     }
  213. }
  214.  
Advertisement
Add Comment
Please, Sign In to add comment