Using keyboard to attack, not mouse

Hi, in my RPG, I wanted to add keyboard controls for melee attacks. This code seems to work fine right now and the enemies are dying when I get in range and attack. Is this fine to use?

void Update()
{
    foreach (Enemy enemy in enemies)
    {
        float distanceFromEnemy = Vector3.Distance(transform.position, enemy.transform.position);
        if (distanceFromEnemy <= attackRadius)
        {
            if (Input.GetButtonDown("Fire1"))
            {
                enemy.TakeDamage(damage);
            }
        }
    }
}

Update: For some reason I am able to kill a couple enemies at the start, but after I get to some enemies, they won’t die or take damage. Any help would be appreciated.

I changed this so there’s a trigger collider around the player and if enemies are in it and you press Fire1 then the enemy takes damage, and it seems to work.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms