using System.Collections; using System.Collections.Generic; using UnityEngine; public class MagicLaser : MonoBehaviour { [SerializeField] private float laserGrowTime = 2f; // Duration for the laser to fully extend private bool isGrowing = true; // Tracks whether the laser is still growing private float laserRange; // The maximum length the laser can reach private SpriteRenderer spriteRenderer; // Reference to the SpriteRenderer component private CapsuleCollider2D capsuleCollider2D; // Reference to the CapsuleCollider2D component private void Awake() { spriteRenderer = GetComponent(); // Get the SpriteRenderer component attached to this GameObject capsuleCollider2D = GetComponent(); // Get the CapsuleCollider2D component attached to this GameObject } private void Start() { LaserFaceMouse(); // Rotate the laser to face the mouse cursor } private void OnTriggerEnter2D(Collider2D other) { // If the laser hits an indestructible object, stop its growth if (other.gameObject.GetComponent() && !other.isTrigger) { isGrowing = false; } } public void UpdateLaserRange(float laserRange) { this.laserRange = laserRange; // Set the laser's maximum range StartCoroutine(IncreaseLaserLengthRoutine()); // Start extending the laser } private IEnumerator IncreaseLaserLengthRoutine() { float timePassed = 0f; // Tracks the elapsed time // Gradually extend the laser until it reaches its maximum range or is stopped while (spriteRenderer.size.x < laserRange && isGrowing) { timePassed += Time.deltaTime; float linearT = timePassed / laserGrowTime; // Adjust the size of the sprite to simulate the laser growing spriteRenderer.size = new Vector2(Mathf.Lerp(1f, laserRange, linearT), 1f); // Adjust the collider size and position as the laser grows capsuleCollider2D.size = new Vector2(Mathf.Lerp(1f, laserRange, linearT), capsuleCollider2D.size.y); capsuleCollider2D.offset = new Vector2((Mathf.Lerp(1f, laserRange, linearT)) / 2, capsuleCollider2D.offset.y); yield return null; } // After the laser stops growing, start fading out the laser's sprite StartCoroutine(GetComponent().SlowFadeRoutine()); } private void LaserFaceMouse() { Vector3 mousePosition = Input.mousePosition; // Get the mouse position on the screen mousePosition = Camera.main.ScreenToWorldPoint(mousePosition); // Convert mouse position to world coordinates Vector2 direction = transform.position - mousePosition; // Calculate the direction from the laser to the mouse transform.right = -direction; // Rotate the laser to face the direction of the mouse } }