Handling enemy collisions

We need to handle collisions between our enemies and ActiveBarriers. Since we have a Rigidbody attached to our Enemy prefab, it will receive the OnTriggerEnter() event when it hits the collider of an ActiveBarrier GameObject.

Once the collisions with ActiveBarriers are implemented, we'll add collisions with the bottom of the screen, which will reduce the player's health.

Collisions with active barriers

First of all, we must disable the ActiveBarrier's collider by default and enable it when the barrier is built in the following manner:

  1. In the Project view, select our ActiveBarrier prefab.
  2. Disable its Box Collider component using its checkbox.
  3. Open the ActiveBarrierController.cs script attached to it.
  4. We will need a new built boolean that will help us know if the barrier has finished its building process. Along with our UISlider and UILocalize variables, declare the following:
    private bool built = false;
  5. Now, add the following two lines at the end of the BuildFinished() method:
    //Set the build value to true and activate collider
    built = true;
    collider.enabled = true;
  6. Ok, now the collider is enabled only when the barrier is built. We can add a HitByEnemy() method with the concerned enemy passed as a parameter that will destroy the barrier and the enemy in the following manner:
    public void HitByEnemy(EnemyController enemy)
    {
      //If the barrier isn't built, don't go further
      if(!built) return;
      //Else, kill the enemy
      StartCoroutine(enemy.Kill());
      //Kill the barrier too
      StartCoroutine(RemoveBarrier());
    }
  7. Here, we start two coroutines: one to kill the enemy and another one to remove the barrier. Let's add the RemoveBarrier() coroutine now with the following code snippet:
    IEnumerator RemoveBarrier()
    {
      //Tween for smooth disappearance
      TweenScale.Begin(gameObject, 0.2f, Vector3.zero);
      //Notify the Viewport that a Barrier has been removed
      transform.parent.SendMessage("BarrierRemoved");
      //Wait for end of tween, then destroy the barrier
      yield return new WaitForSeconds(0.2f);
      Destroy(gameObject);
    }

    The coroutine in the previous code scales down the barrier before it is destroyed. We send a message to the parent (Viewport) because we need to decrease the barrierCount value.

  8. Let's add the BarrierRemoved() method in the ViewportHolder.cs script. In the Hierarchy view, select our Viewport GameObject and open the ViewportHolder.cs script attached to it.
  9. In our ViewportHolder.cs script, add the following new BarrierRemoved() method:
    void BarrierRemoved()
    {
      //Decrease the barrierCount value
      barrierCount--;
    }
  10. The barrierCount value will be updated as soon as a barrier is destroyed. Now, let's open the EnemyController.cs script and add the Kill() coroutine as shown in the following code snippet:
    public IEnumerator Kill()
    {
      //Tween for smooth disappearance
      TweenScale.Begin(gameObject, 0.2f, Vector3.zero);
      //Deactivate the collider now
      collider.enabled = false;
      //Wait end of tween, then destroy the enemy
      yield return new WaitForSeconds(0.2f);
      Destroy(gameObject);
    }
  11. Great! All of our coroutines and methods are ready. Now, we need to call the HitByEnemy() method of the concerned ActiveBarrier when a collision occurs.
  12. We just have to add the following OnTriggerEnter() method inside our EnemyController.cs script, which will call this method only if the collided object actually is a barrier:
    void OnTriggerEnter(Collider other)
    {
      //Store the collided object's ActiveBarrierController
      ActiveBarrierController barrierController = other.GetComponent<ActiveBarrierController>();
      //If it has a BarrierController, call HitByEnemy
      if(barrierController != null)
      barrierController.HitByEnemy(this);
    }
  13. Save all of the scripts and click on the play button.

If you place a barrier on an enemy's trajectory, both of them will be destroyed when they collide! If the building process isn't over, nothing happens.

In the case where a barrier finishes its building process while an enemy is still inside it, a collision will occur. Perfect!

Now that the player can destroy his or her enemies, let's add a way for the enemies to destroy the player.

Colliding with the bottom of the screen

We can now add a collider at the bottom of the viewport's background that will destroy enemies and reduce the player's health. Before we do this, let's create a Healthbar with a HealthController script.

Healthbar

To create this Healthbar, we need the Button.png file available in the Assets.zip file. If you haven't added it to the Game Atlas as a sliced sprite yet, please do so before you continue.

We will use a Progress Bar to create a Healthbar on which we will add a HealthController.cs script to handle the display of damage and health points. Perform the following steps to do so:

  1. In the Hierarchy view, select the UI GameObject from Anchor.
  2. Open the Widget Tool window by navigating to NGUI | Create a Widget. Then perform the following steps:
    1. Select our Game Atlas.
    2. Select the Progress Bar template.
    3. Select our Button sprite for the Empty field.
    4. Select our Button sprite for the Full field.
    5. With our UI GameObject selected, click on the Add To button.
  3. Select the new Progress Bar GameObject and rename it as Healthbar.
  4. Attach an Anchor to it by navigating to NGUI | Attach. Then perform the following steps:
    1. Drag our Viewport GameObject in the Container field.
    2. Set the Side parameter to Top.
    3. Set Pixel Offset to {-160, -30}.
  5. Select the Background GameObject from Healthbar and perform the following steps:
    1. Set Color Tint to {255, 120, 120, 140}.
    2. Set Dimensions to 320 x 42.
    3. Change Sprite Type to Sliced.
    4. Click on the Edit button next to the Sprite field.
    5. Set all four border values to 6 for slicing parameters.
  6. Select the Foreground GameObject from Healthbar and then perform the following steps:
    1. Set Color Tint to {25, 245, 255, 255}.
    2. Set Dimensions to 320 x 42.
    3. Change Sprite Type to Sliced.

Ok, we have a configured health bar centered at the top of the screen. We need to add a script to it that will handle health points and modify the value of Slider accordingly. The steps to do so are as follows:

  1. In the Hierarchy view, select our Healthbar GameObject.
  2. Create and add a new HealthController.cs script to it.
  3. Open this new HealthController.cs script.

In this new script, we will save a static reference to the instance of the HealthController class so that its methods are easily accessible from other scripts. First, let's declare necessary variables and initialize them on Awake() as shown in the following code:

//Static variable that will store this instance
public static HealthController Instance;
//We will need the attached slider and a HP value
private UISlider slider;
private float hp = 100;

void Awake()
{
  //Store this instance in the Instance variable
  Instance = this;
  //Get the slider Component
  slider = GetComponent<UISlider>();
}

Ok, our variables are now initialized correctly. Let's create a Damage() method that will reduce the hp value and update the slider as follows:

public void Damage(float dmgValue)
{
  //Set new HP value with a clamp between 0 and 100
  hp = Mathf.Clamp(hp - dmgValue, 0, 100);
  //Update the slider to a value between 0 and 1
  slider.value = hp * 0.01f;
  //If hp <= 0, restart level
  if(hp <= 0)
  Application.LoadLevel(Application.loadedLevel);
}

Great! The Damage() method is ready. Let's create the EndOfScreen widget that will collide with the enemies.

The EndOfScreen widget

Let's create the EndOfScreen widget that will help detect enemy collisions as follows:

  1. In the Hierarchy view, select our Viewport GameObject and perform the following steps:
    1. Create a new child by pressing Alt + Shift + N.
    2. Rename this new child as EndOfScreen.
  2. Attach a collider to it by navigating to NGUI | Attach a Collider and set Size to {3840, 43, 1}.
  3. Attach Anchor to it by navigating to NGUI | Attach.
    1. Drag the Background GameObject from Viewport in the Container field.
    2. Set its Side parameter to Bottom.
    3. Set its Pixel Offset to {0, 33}.
  4. Click on the Untagged / Add Tag… button at the top of the Inspector view.
  5. Create a new DamageZone tag.
  6. Select our EndOfScreen GameObject.
  7. Set Tag to DamageZone.
  8. Make sure our EndOfScreen GameObject is selected.
  9. Create a new sprite by navigating to NGUI | Create | Sprite and perform the following steps:
    1. Set its Atlas type to the SciFi Atlas.
    2. Set its Sprite type to the Honeycomb sprite.
    3. Set its Sprite Type to Tiled.
    4. Set its Color Tint values to R: 255, G: 120, B: 120, and A: 255.
    5. Set its Depth value to 2.
    6. Set its Dimensions parameter to 3840 x 43.

Good. We now have an EndOfScreen limit with a sprite and a collider. Now, we need to edit our EnemyController.cs script's OnTriggerEnter() method to check if the collided object has the DamageZone tag and hurt the player if needed. Perform the following steps to do so:

  1. In the Project view, select our SpaceShip prefab and open the EnemyController.cs script attached to it.
  2. Within the EnemyController.cs script, at the very first line of the OnTriggerEnter() method, add the following lines to check if the collided object has a DamageZone tag:
    //Is the collided object a DamageZone?
    if(other.CompareTag("DamageZone"))
    {
      //In that case, hurt the player
      HealthController.Instance.Damage(30f);
      //Then, kill the enemy and don't go further
      StartCoroutine(Kill());
      return;
    }
  3. Save all of the scripts and click on the play button. Now, our enemies are destroyed when they collide with the end of the Viewport, and the player's health is decreased!

Now, let's add another way to destroy our enemies.

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

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