MiniGames/Assets/Scripts/BalloonFloat/ShieldController.cs
2025-07-14 19:30:52 +05:00

103 lines
3.0 KiB
C#

using System.Collections.Generic;
using UnityEngine;
public class ShieldController : MonoBehaviour
{
public float followSpeed = 20f;
public float pushForce = 10f;
public LayerMask pushableLayers;
private Rigidbody2D rb;
private Camera mainCam;
private HashSet<GameObject> hitEnemies = new HashSet<GameObject>();
void Start()
{
rb = GetComponent<Rigidbody2D>();
mainCam = Camera.main;
}
void Update()
{
if (BalloonGameManager.IsGameOver) return;
HandleMovement();
DestroyOffscreenEnemies();
}
void HandleMovement()
{
if (Input.GetMouseButton(0))
{
Vector2 touchPosition = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (touchPosition - rb.position);
rb.velocity = direction * followSpeed;
}
else
{
rb.velocity = Vector2.zero;
}
// Clamp shield inside the camera
Vector3 viewPos = mainCam.WorldToViewportPoint(transform.position);
viewPos.x = Mathf.Clamp01(viewPos.x);
viewPos.y = Mathf.Clamp01(viewPos.y);
transform.position = mainCam.ViewportToWorldPoint(viewPos);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (((1 << collision.gameObject.layer) & pushableLayers) != 0)
{
Rigidbody2D otherRb = collision.rigidbody;
if (otherRb != null && otherRb != rb)
{
Vector2 forceDir = collision.transform.position - transform.position;
forceDir.Normalize();
otherRb.AddForce(forceDir * pushForce, ForceMode2D.Impulse);
// Add to list of hit enemies
if (!hitEnemies.Contains(collision.gameObject))
{
hitEnemies.Add(collision.gameObject);
}
}
}
}
void DestroyOffscreenEnemies()
{
float buffer = 1f; // World units to extend camera bounds (adjust as needed)
List<GameObject> toRemove = new List<GameObject>();
foreach (GameObject enemy in hitEnemies)
{
if (enemy == null) continue;
Vector3 enemyPos = enemy.transform.position;
Vector3 camPos = mainCam.transform.position;
float camHeight = 2f * mainCam.orthographicSize;
float camWidth = camHeight * mainCam.aspect;
float left = camPos.x - camWidth / 2f - buffer;
float right = camPos.x + camWidth / 2f + buffer;
float bottom = camPos.y - camHeight / 2f - buffer;
float top = camPos.y + camHeight / 2f + buffer;
if (enemyPos.x < left || enemyPos.x > right ||
enemyPos.y < bottom || enemyPos.y > top)
{
Destroy(enemy);
toRemove.Add(enemy);
}
}
foreach (GameObject e in toRemove)
{
hitEnemies.Remove(e);
}
}
}