2D Melee Attack Tutorial for Unity

The Unity Engine provides an extensive platform for creating both 2D and 3D games. One of the foundational elements in many action games is the melee attack. In a 2D environment, such an attack often consists of a character swinging a weapon or throwing a punch, and it can be accomplished using a combination of Unity animations, physics, and scripting tools.

Prerequisites

1. Setting up the Project and Scene

  • Create a new 2D Unity project (if haven't yet).
  • Import or create a character sprite. Place it in the scene.

2. Setting up the Melee Attack Animation

  • In the Project window, right-click and create an "Animator Controller". Name it "CharacterAnimator".
  • Assign this animator to the character by selecting the character and dragging the animator to the "Animator" component.
  • Open the Animation window. With the character selected, create a new animation named "MeleeAttack".
  • For simplicity, let's assume this attack is a quick punch. Animate the sprite to simulate this action.

3. Creating the Attack Hitbox

  • Add an empty GameObject as a child to the character. This will act as the hitbox for the attack.
  • Attach a "Box Collider 2D" to the empty GameObject. Adjust its size and position to match where the character would hit during the punch.
  • Deactivate the hitbox by unchecking its "Active" box. This ensures it only activates during the attack animation.

4. Scripting the Attack Logic

  • Create a new script, name it "MeleeAttack" then paste the code below inside it:

'MeleeAttack.cs'

using UnityEngine;

public class MeleeAttack : MonoBehaviour
{
    private Animator animator;
    private BoxCollider2D hitbox;

    private void Start()
    {
        animator = GetComponent<Animator>();
        hitbox = transform.Find("HitboxGameObjectName").GetComponent<BoxCollider2D>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // Attack on Space key press.
        {
            animator.SetTrigger("MeleeAttack");
            Invoke("ActivateHitbox", 0.2f); // Activate hitbox after 0.2 seconds.
            Invoke("DeactivateHitbox", 0.4f); // Deactivate hitbox after 0.4 seconds.
        }
    }

    void ActivateHitbox()
    {
        hitbox.gameObject.SetActive(true);
    }

    void DeactivateHitbox()
    {
        hitbox.gameObject.SetActive(false);
    }
}

5. Handling Collisions

  • Change the tags of the enemy game objects to "Enemy".
  • Create a new script, name it "Hitbox" then paste the code below inside it:

'Hitbox.cs'

using UnityEngine;

public class Hitbox : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            // Damage or destroy the enemy.
            Destroy(collision.gameObject);
        }
    }
}
  • Attach the script "Hitbox" to the hitbox object.

Questions to Address:

  1. How does the hitbox know when to activate during the animation?: The hitbox is activated by the 'Invoke' function in the 'MeleeAttack.cs' script. The timing can be adjusted based on the frame where the attack is supposed to land.
  2. What happens if the hitbox collides with multiple enemies at once?: Using the provided 'Hitbox' script, each enemy with the tag "Enemy" that collides with the hitbox will be destroyed. Adjust the script to manage damage or other effects.
  3. Can the attack button be changed from the Space key?: Yes, in the 'MeleeAttack.cs' script, the line if ('Input.GetKeyDown(KeyCode.Space)') checks for the Space key press. Replace 'KeyCode.Space' with another 'KeyCode' value to change the attack button.

Conclusion

This guide provides a basic framework for implementing a 2D melee attack in Unity. Enhancements such as adding sound effects, visual feedback, and refining the hit detection logic can further enhance the melee attack experience.

Links
Unity 6