R
R
RZC2022-01-22 21:24:13
C++ / C#
RZC, 2022-01-22 21:24:13

Why does the enemy die from a different number of hits?

As part of self-study, I repeated the attack script from one YouTube channel. The script looks like this:

Player script

void Update()
{if (timeBtwAttack <= 0)
        {
            timeBtwAttack = startTimeBtwAttack;
        }
        else
        {
            timeBtwAttack -= Time.deltaTime;
        }
        //нанесение удара
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Attack();   
        }
}
void Attack()
    {
        //Воспросизвести анимацию аттаки
        anim.SetTrigger("Attack");
        //обнаружить всех врагов в зоне действия
       Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);

        //Нанести урон
        for (int i = 0; i < hitEnemies.Length ; i++)
        {
            hitEnemies[i].GetComponent<FollowingEnemyHP>().GetDamage(firstAttackDamage);
        }
    }

    private void OnDrawGizmosSelected()
    {
        if (attackPoint == null)
            return;

        Gizmos.DrawWireSphere(attackPoint.position, attackRange);
    }


Gizmo is set like this:
61ec4a7cf32de881238097.png
Damage is set to 20. The enemy is set to 100. But it happens that when dealing damage, the enemy dies in 2 hits. Why is that?

Enemy script:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowingEnemyHP : MonoBehaviour
{
    private float currentHealth;
    public float health = 100;
    private float damage = 0.1f; // урон наносимый игроку


    private void Start()
    {
        currentHealth = health;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.name == "Player")
        {
            collision.GetComponent<PlayerHP>().TakeDamage(damage);
        }
    }

    public void GetDamage(float amount)
    {
        currentHealth -= amount;
        if (currentHealth <= amount)
        {
            Die();
        }

        void Die()
        {
           
            Destroy(gameObject);

        }
    }
}





Please advise how to correct this misunderstanding.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrGreger, 2022-01-23
@RZC

Your attack code

if (Input.GetKeyDown(KeyCode.Space))
{
  Attack();   
}

is outside your timer code and is called every frame
if (timeBtwAttack <= 0)
{
  timeBtwAttack = startTimeBtwAttack;
     
  //нанесение удара 
  if (Input.GetKeyDown(KeyCode.Space))
  {
    Attack();   
  }
}
else
{
  timeBtwAttack -= Time.deltaTime;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question