Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity Game Development Blueprints

You're reading from   Unity Game Development Blueprints Explore the various enticing features of Unity and learn how to develop awesome games

Arrow left icon
Product type Paperback
Published in Nov 2014
Publisher
ISBN-13 9781783553655
Length 318 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
John P. Doran John P. Doran
Author Profile Icon John P. Doran
John P. Doran
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. 2D Twin-stick Shooter 2. Creating GUIs FREE CHAPTER 3. Side-scrolling Platformer 4. First Person Shooter Part 1 – Creating Exterior Environments 5. First Person Shooter Part 2 – Creating Interior Environments 6. First Person Shooter Part 3 – Implementing Gameplay and AI 7. Creating Save Files in Unity 8. Finishing Touches 9. Creating GUIs Part 2 – Unity's New GUI System Index

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. Exit the game and 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.

    Note

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

  4. Drag-and-drop this newly added behavior onto our enemy object.
  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, 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 will print something onto your console, which may help you when debugging your own code in the future.

  2. Save the file, and then go back into Unity. Attach the EnemyBehaviour behavior to your enemy object. For collision events to register we need to add a Rigidbody 2D component to our enemy by going to Component | Physics 2D | Rigidbody 2D. Change the Gravity Scale to 0 so it will not fall. Have a look at the following screenshot:
    Creating enemies

    Note

    OnCollisionEnter2D is a function that will trigger when two objects with 2D colliders collide. It is important to note collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached (which we just did).

    For more info on OnCollisionEnter2D check out http://docs.unity3d.com/ScriptReference/Collider2D.OnCollisionEnter2D.html.

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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime