Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.0 kB
1
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public abstract class BrickBase : MonoBehaviour
{
    public float maxHp;
    public Sprite fullHpSprite;
    public Sprite halfHpSprite;
    int ballDamage = 1;
    SpriteRenderer spriteRenderer;
    float currentHp;
    float minCurrentHp = 0;
    TextMeshPro brickText;
    protected GameManager gameManager;
    bool spriteChange;

    public virtual void Awake()
    {
        gameManager = FindObjectOfType<GameManager>();
        brickText = GetComponentInChildren<TextMeshPro>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        currentHp = maxHp;
    }

    public virtual void Start()
    {
        gameManager.BrickIsBorn();
        brickText.text = currentHp.ToString();
    }

    public void Damage(int damage)
    {
        currentHp-=damage;

        if (currentHp >= 0)
        {
            brickText.text = currentHp.ToString();
        }
        else 
        {
            brickText.text = minCurrentHp.ToString();
        }
        
        if (((maxHp - currentHp) / maxHp) >= 0.5f && !spriteChange)
        {
            spriteChange = true;
            spriteRenderer.sprite = halfHpSprite;
        }

        if (currentHp <= 0) // <-- !!! This will probably need to be changed to '==' to avoid Die() to be called more than once for a same Brick before it actually disappears
        {
            Dead();
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        //We check if the colliding object is a ball
        Ball collidingBall = collision.gameObject.GetComponent<Ball>();
        //returns a reference to the Ball component of the incoming game object
        //(returns null if there is no Ball component)

        if (collidingBall != null) //if collidingBall is not a null object...
        {
            Damage(ballDamage);
        }
    }

    public abstract void Dead();

}