Gaming in Unity

16. Unity 2D Game 12 - Projectile Reaction

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-12-projectile-reaction-header.png)

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:

if(!walking){
    return;
}

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-projectile-reaction-step-1.jpg)

And now add a function to help the Robot dance:

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

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-projectile-reaction-step-1-2.jpg)

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) {
    e.Dance();
}

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

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-projectile-reaction-step-1-3.jpg)

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.

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-projectile-reaction-step-2.jpg)

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

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-projectile-reaction-step-2-2.jpg)

Click on the Transition then disable HasExitTime.

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-projectile-reaction-step-2-3.jpg)

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.

(../img/unity-16-2d-game-12-projectile-reaction/2d-game-projectile-reaction-step-2-4.jpg)

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

animator.SetTrigger("Dancing")

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

Created by: David Corish