Enemy Setup — Spider Ranged Attack
In this article, we will create the attack of the Spider. The Spider will fire a ranged acid ball in the direction of the Player when the Player comes within range.
The Acid Effect script is attached to the projectile fired by the Spider. It contains a few variables to control the movement and lifetime of the shot.
- The number of units the projectile moves per second.
- The amount of time before the projectile destroys itself.
- A bool to know which direction to move the shot.
In Start, we set the GameObject to destroy itself after the delay.
In Update, we move the projectile left or right depending on the bool.
The Set Move Direction method allows us to set the direction of movement when the projectile instantiates.
In OnTriggerEnter2D, we check if the other Collider belongs to the Player, grab the IDamageable interface, and call the Damage method.
In the Spider script, we add a variable for the acid projectile prefab.
In Update, we call the Flip method from Enemy passing in the Player transform while the Spider is alive.
The Attack method instantiates the acid prefab at the Spider’s position. Then we grab the Acid Effect script component and call Set Move Direction passing in the FlipX from the sprite renderer.
The Spider Animation Event script is attached to the Sprite GameObject so the Animation Event can use it. We need a variable for a reference to the Spider script.
In Start, we get the reference Spider script component from the parent.
The Fire method is public to be used by an Animation Event, and it calls the Attack method on the Spider.
To create an Animation Event, we go to the Animation window, select the point where we want the Event to occur, and click the Add Event button. Then we can choose the Event in the Animation and pick which method we want it to call.
In the Enemy script, we add a method called when the Player is near the Enemy to set the InCombat bool on the Animator.
The Player Detector script tells the Enemy when the Player is nearby. The Detector consists of a large Box Collider 2D set to be a trigger and a Rigidbody 2D on the container object for the Spider Prefab.
n the Player Detector script, we need to reference the Enemy script from the child GameObject, which we get in Start. In OnTriggerEnter and Exit, we call the Player Nearby method on the Enemy, passing in true or false to let the Enemy know the Player has entered or left the Collider.
When the Player enters the Collider, the Spider starts firing acid projectiles and faces the Player.