BlockScript.cs 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using UnityEngine;
  2. [RequireComponent(typeof(Collider2D))]
  3. public class blockScript : MonoBehaviour
  4. {
  5. [SerializeField] private float health = 1f;
  6. private float _currentHealth;
  7. private bool _isDestroyed;
  8. void Awake()
  9. {
  10. _currentHealth = health;
  11. }
  12. private void OnCollisionEnter2D(Collision2D collision)
  13. {
  14. if (!collision.gameObject.CompareTag("Ball"))
  15. return;
  16. BallScript ball = collision.gameObject.GetComponent<BallScript>();
  17. float damage = ball != null ? ball.GetDamageAgainstBlock(this, collision) : 1f;
  18. ApplyDamage(damage);
  19. ball?.NotifyHitBlock(this, collision);
  20. }
  21. public void ApplyDamage(float amount)
  22. {
  23. if (_isDestroyed)
  24. return;
  25. float clampedAmount = Mathf.Max(0f, amount);
  26. _currentHealth -= clampedAmount;
  27. if (_currentHealth <= 0f)
  28. {
  29. _isDestroyed = true;
  30. Destroy(gameObject);
  31. GameManager.Instance?.OnBlockDestroyed();
  32. }
  33. }
  34. }