Gaming in Unity

16. Unity 2D Game 12 - Projectile Reaction


Now we can add a reaction to Robot when coming into contact with Projectile!

Step 1 - Modifying EnemyController Script

We now need to add some code to EnemyController so that the Robot responds when it comes into contact with the projectile.

Open EnemyController.

Create a bool called walking and initialise it to true:

bool walking = true;

Add a check to FixedUpdate( ). This will stop the Robot from moving:



And now add a function to help the Robot dance:

public void Dance() {
    walking = false;
    rigidbody2D.simulated = false;


Finally, open the Projectile Script to make some final modifications.

In void OnCollisionEnter2D(Collision2D other), add:

EnemyController e = other.collider.GetComponent < EnemyController > ();
if (e != null) {

This checks if the Robot exists and then activates Dance if it does.


Step 2 - Animating Dancing Robot

Refer back to the previous guide for more detail on animation.

Create a new animation clip for the Robot called RobotDancing.anim.


Double-click on the Robot prefab and right-click on the Blend Tree. Click Make Transition and then connect it to RobotDancing.


Click on the Transition then disable HasExitTime.


Click on parameters at the left and add a new Trigger called Dancing

Click on the Blend Tree and add Dancing as a condition for the transition.


And now add one more line to public void Dance( ) in EnemyController.cs:


The robot will now dance when it comes into contact with the projectile!

Created by: David Corish