MiniGames/Assets/ShieldController.cs
2025-07-11 15:42:48 +05:00

47 lines
1.4 KiB
C#

using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class ShieldController : MonoBehaviour
{
public float followSpeed = 20f; // How fast the shield follows your finger
public float pushForce = 10f; // Force applied to obstacles
public LayerMask pushableLayers; // Only apply force to selected layers
private Rigidbody2D rb;
private Camera mainCam;
void Start()
{
rb = GetComponent<Rigidbody2D>();
mainCam = Camera.main;
}
void Update()
{
if (Input.GetMouseButton(0)) // For both mobile and desktop
{
Vector2 touchPosition = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (touchPosition - rb.position);
rb.velocity = direction * followSpeed;
}
else
{
rb.velocity = Vector2.zero; // Stop when not dragging
}
}
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);
}
}
}
}