Exemplo n.º 1
0
    public void ReceiveDamage(int damageReceived, bool friendlyFire = false)
    {
        _hitpoints -= damageReceived;

        _damageShowTimeout = 0.0f;
        _showDamageBar     = !friendlyFire;

        _damageIndicatorBar.Damage(damageReceived);

        // Excerpt from https://docs.unity3d.com/Manual/ExecutionOrder.html
        //
        // "FixedUpdate: FixedUpdate is often called more frequently than Update.
        // "It can be called multiple times per frame, if the frame rate is low and it may not be called between frames at
        // "all if the frame rate is high. All physics calculations and updates occur immediately after FixedUpdate."
        //
        // Collision handling is happening after FixedUpdate, which in turn can be called multiple times per frame.
        // Destroy only marks object for destroy, which will happen only in the next frame.
        // So to prevent entering the condition multiple times, we use a boolean flag.
        if (_hitpoints <= 0 && !_isDestroying)
        {
            _isDestroying = true;

            if (!friendlyFire)
            {
                if (this is EnemyWeak)
                {
                    _app.Score += GlobalConstants.EnemyWeakScore;
                }
                if (this is EnemyMedium)
                {
                    _app.Score += GlobalConstants.EnemyMediumScore;
                }
                if (this is EnemyHeavy)
                {
                    _app.Score += GlobalConstants.EnemyHeavyScore;
                }

                _app.ScoreCount.text = _app.Score.ToString();
            }

            var explosion = Instantiate(DeathAnimation, new Vector3(RigidbodyComponent.position.x, RigidbodyComponent.position.y, -1.0f), Quaternion.identity);
            var ps        = explosion.GetComponent <ParticleSystem>().main;
            ParticleSystem.MinMaxGradient g = new ParticleSystem.MinMaxGradient(_originalColor);
            ps.startColor = g;

            Destroy(explosion, 2.0f);

            Destroy(_damageIndicatorBar.gameObject);
            Destroy(gameObject);
        }
    }