Creating enemies

Now, it's really cool that we have a player, but it'll get really boring if all we can do is move around and shoot some lasers in the dark. Next, we'll introduce some simple enemies that will move toward the player that we'll be able to shoot later. Perform the following steps:

  1. Leave the game by pressing the Play button again and then access our example code's Assets folder; move the enemy.png file into our Sprites folder.
  2. Following that, drag and drop it into your scene from the Scene tab to place it in the level.
  3. Right-click on the Scripts folder you created earlier, click on Create, and select the C# Script label. Call this new script MoveTowardsPlayer. Go to MonoDevelop and use the following code:
    using UnityEngine;
    using System.Collections;
    
    public class MoveTowardsPlayer : MonoBehaviour 
    {
      private Transform player;
      public float speed = 2.0f;
    
      // Use this for initialization
      void Start () 
      {
        player = GameObject.Find("playerShip").transform;
      }
      
      // Update is called once per frame
      void Update () 
      {
        Vector3 delta = player.position - transform.position;
        delta.Normalize();
        float moveSpeed = speed * Time.deltaTime;
        transform.position = transform.position + (delta * moveSpeed);
      }
    }

    In the beginning of the game, I find the player ship and get his Transform component. Then, in every frame of the project, we move the enemy from where it currently is to the direction where the player is at.

    The GameObject.Find function is very useful as it allows us to access objects at any time, but is computationally expensive, so don't put it in a function that gets called often (such as Update) when you can just save a reference to it. It's also important to note that the spelling of the parameter has to be exactly the same as the object's name in the hierarchy; so be sure to double check when you use it.

    Note

    If you ever want to have objects run away from the player, use a negative speed.

  4. Drag and drop this newly added behavior onto our enemy object and rename it to Enemy.
  5. Next, add a circle collider to our enemy by going to Component | Physics 2D | Circle Collider 2D. Change the Radius property to .455, and run the game. Have a look at the following screenshot:
    Creating enemies

Now, you'll see that the enemy will always move toward you! But if we shoot it, nothing happens. Let's fix that as follows:

  1. Right-click on the Scripts folder you created earlier, click on Create, and select the C# Script label. Call this new script EnemyBehaviour. Go to MonoDevelop (your IDE of choice,), and use the following code:
    using UnityEngine; // MonoBehaviour
    
    public class EnemyBehaviour : MonoBehaviour 
    {
    
      // How many times should I be hit before I die
      public int health = 2;
    
      void OnCollisionEnter2D(Collision2D theCollision)
      {
        // Uncomment this line to check for collision
        //Debug.Log("Hit"+ theCollision.gameObject.name);
    
        // this line looks for "laser" in the names of 
        // anything collided.
        if(theCollision.gameObject.name.Contains("laser"))
        {
          LaserBehaviour laser = theCollision.gameObject.GetComponent("LaserBehaviour") as       LaserBehaviour;
          health -= laser.damage;
          Destroy (theCollision.gameObject);
        }
        
        if (health <= 0) 
        {
          Destroy (this.gameObject);
        }
      }
    }

    Now, you will notice that we have commented a line of code calling the function Debug.Log. This function when called will print something onto your console (in this case, name the object that we collided with), which may help you when debugging your own code in the future.

    It's also important to note the reason we ask if the name contains Laser instead of is equal to is because when you create an object using Instantiate, by default it will add " (Clone)" to the end of the name of the object.

  2. We also want to tell the objects to actually react to collision events so we will need to add Rigidbody 2D physics to the object, which is required one of the two objects involved in a collision in order for OnCollisionEnter2D to be called.
  3. Select the Enemy object and then select Component | 2D Physics | Rigidbody 2D. From there, change the GravityScale value to 0 so that the object will not fall down by default due to gravity.
  4. Save your script, and then go back into Unity. Attach the EnemyBehaviour behavior to your enemy object, save your project, and run the game. If all went well, we should have something like the following screenshot:
    Creating enemies

Now, whenever we hit the enemy with our bullets twice, it will die. Nice!

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

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