Next, let’s equip the player with a sword instead. Check the FileSystem. Just like the gun, several sword images can be found in templates > objects > weapons > P_other.
Add your preferred sword as a child of B_Weapon. Here, we’ll use W_001_sword.png.
Let’s add an attack hitbox to the sword. The object already has an AttackArea, but it’s currently placed at the player’s feet. Move AttackArea2D to be a child of B_Weapon.
Now adjust the size and position of AttackCollision. Since the position and rotation may be off, reset them both to 0. Also, the default hitbox looks a bit too short, so let’s make the shape longer. Note: adjusting the shape may automatically change the x-coordinate.
Play the Swing animation again. The hitbox should now move along with the sword.
Explanation:
Attack Hitboxes for Sprite Characters
For characters created using sprite sheets, it’s a good idea to adjust the attack hitbox size and position based on the animation.
In the Inspector, expand the Shape property of CollisionShape2D.
You can set keyframes to animate the shape size and position as part of the attack motion.
Now the close-range sword attack should be functional. Test it out—if everything is set up correctly, pressing the Y button (V on keyboard) should let the player slash with a sword and defeat zombies.
However, you might notice a couple of issues:
The sword is always visible, and even during shooting the gun doesn’t appear. → You’ll need a way to switch between sword and gun.
Zombies take damage even when you’re not attacking, just by touching the sword. → This happens because the sword’s hitbox is always active.
Now try a test play.
Both the sword and gun should be hidden, and zombies shouldn’t take damage from body contact.
However, since they stay hidden, we now need to enable them appropriately.
In the Sword state, reverse the settings.
Add two actions:
First, ChangeObjectProperty to turn on the Visible property of W001Sword.
Test again.
The gun should now only appear when shooting.
TIPS: Switching Properties Using Animation
In this course, we used ChangeObjectProperty actions to toggle sprite visibility.
However, you can also control properties like Visible or Disabled through animations, by setting them as keyframes.
But be cautious:
If an animation is interrupted before reaching the keyframe, the change might not take effect properly.
For example, some animations like 026_Crouch use this technique to switch facial expressions via animated polygons.
For more on using AnimationPlayer, refer to the Graphics Course.