Beetle attacks player on the ground

Currently, when our Cucumber Man collides with a Cucumber Beetle, the Die animation is played, but no other behaviors are implemented. In this section, we will modify the necessary scripts for the following to occur each time the Cucumber Man collides with a Cucumber Beetle:

  • Beetle faces Cucumber Man
  • Beetle attacks Cucumber Man for specified time
  • Beetle's die animation plays
  • Beetle is removed from game

We will use the following three lines of code inside our OnCollisionEnter() method to force the beetle to face the Cucumber Man when there is a collision. As you can see from the following code, we create a variable to make it easy to reference the Cucumber Man and then a second variable for the Cucumber Man's current transform. The third line of code tells the current Cucumber Beetle to face the Cucumber Man:

var cm = GameObject.Find ("CucumberMan");
var tf = cm.transform;
this.gameObject.transform.LookAt (tf);

Now, we just need to edit the OnCollisionEnter method to include two statements. The first statement plays the Attacking on Ground animation. The second statement makes a call to the function that will destroy the current Cucumber Beetle. Here are those two lines of code:

animator.Play ("Attacking on Ground");
StartCoroutine ("DestroySelf");

The last change to the BeetleNPC script is the DestroySelf() function. We are using this function to simulate the battle and end of life for the current Cucumber Beetle. There are three statements inside the function. The first statement simulates the attack time. The second statement plays the Die on Ground animation. The final line destroys the game object, which is the current Cucumber Beetle:

IEnumerator DestroySelf() {

yield return new WaitForSecondsRealtime (4);
animator.Play ("Die on Ground");
Destroy (this.gameObject, 4);
}

We have two changes to make to our BeetlePatrol script. First, as you can see in the following code, we will add the new isAttacking variable:

 public static bool isDie, isEating, isAttacking =</span> false; 

Our final change to the BeetlePatrol script is to update the conditional statement, as shown in the following code. Now, we will stop the patrol if the beetle is dying, eating, or attacking:

void Update () {

if (!isDie && !isEating && !isAttacking)) {
transform.eulerAngles = Vector3.Slerp (transform.eulerAngles,
targetRotation, Time.deltaTime * directionChangeInterval);
var forward = transform.TransformDirection (Vector3.forward);
controller.SimpleMove (forward * speed);
}
}

We will make additional modifications to the scripts and behaviors in Chapter 10, Scripting Our Points System.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset