Spitting spider attack
Objective: Create an acid spit attack for a spider using animation event.
Select the Sprite child of Spider, as shown below.
Open the animation window and create an animation Attack and save it under Sprites > Animation > Spider. Now drag Spider_Attack_0 to 30 into the animation window timed to play over one second and add an event at 0:24 seconds.
With the Spider’s Sprite selected, open the animator window and add a transition from Idle to Attack and visa versa, shown below. Both use has exit time but the transition duration is zero. The spider’s sprite will Idle then Attack and Idle again in a loop.
The Sprite needs a script, FireSpiderAcid, to use the animation event to trigger the acid to fire. Set layer for the Sprite to Enemy. Set sprite renderer order in layer to 50.
The FireAcidScript is shown below. This scripts grabs a _spider reference and has the FireAcid method, which calls the _spider.Attack() method. In the Sprite animation window select the event and use the function menu to select FireAcid() for the event.
The Attack() method on the Spider script is shown below. This method instantiates the _acid at the Spiders position, _acidTrans, offset to align with the animation.
The Attack() method requires the variable assignments shown below. Importantly, the _acid game object is required.
Drag the Acid_0 sprite into the hierarchy to create the Acid game object. With Acid selected open the animation window and create Acid animation, saving in the Sprites > Animation > Spider folder. Drag Acid_0 to 15 into the animation window set to play over 0:30 seconds. Add a rigidbody 2D with gravity of one and two box collider 2D, one with is trigger checked and the other to detect the floor. Create a new script named SpiderAcid. The layer for the Acid is EnemyAttack and the layer is 50 for the sprite renderer. The Enemy and EnemyAttack layers were previous set so they do not interact. Drag this object into the prefabs folder and delete the Acid in the hierarchy window.
Assign the Acid prefab to _acid in the Spider_Enemy inspector, see below.
The SpiderAcid script is shown below. The _rigidbody is used to set an initial velocity in void Start(), and allow it to be effected by gravity. The Acid blob will be destroyed after five seconds. If the acid collides with the Player, i.e. other, via OnTriggerEnter2D, the IDamagable interface, hit, is used to call the required Damage() method on Player.
The Acid now shoots out a short distance and rolls along the floor, damaging the Player if it hits them. Allowing the Acid blob to move along the floor is a greater threat to the Player.
This article uses assets from GameDevHQ Filebase.