Setting up the Spider Attack in Unity
In my last article, I set up the attack for the moss giant. Now I need to set up the attack for the last enemy type in my game. The spider is unique from the other enemies in the game as it has a projectile attack.
To start, we can create the attack animation in the animation window.
We will also create the animation for the projectile the spider will be attacking with. This will use its own animator. This will also be a prefab and is set up similar to the enemies where you take the first sprite and add the animator to it.
The projectile will also have a circle collider 2D and a rigid body 2D.
Set up the animator to allow the attack animation to play only when the spider is in combat.
In the attack animation for the spider go to about where the spider would shoot the projectile and add an event to the frame.
This will give you the option to select a function in the inspector.
To create a function for this make a new script and add a fire method to it. This will be how you instantiate the projectile. You will also want to add a reference to the projectile and instantiate it in the method.
Add this script to the spider sprite and select the fire method for the function.
Now that it is instantiating projectiles, we can give them directions.
Create a new script and attach it to the projectile game object. This script will have a start method to set the projectile to destroy after five seconds, an update method to move the projectile to the right, and an OnTriggerEnter2D method to detect an IDamageable component to call the damage method.
In the spider script, you will want to override the update and movement methods to make them unique to the spider. The spider will be stationary and will only attack if the player gets close enough.
Now make sure the spider is on the enemy layer and that the projectile is on the enemy attack layer.
This will give you a spider that will attack if you get too close.