Book Image

Learning Unity 2D Game Development by Example

By : Venita Pereira
Book Image

Learning Unity 2D Game Development by Example

By: Venita Pereira

Overview of this book

<p>If you are looking for a guide to create 2D games using Unity, look no further. With this book, you will learn all the essentials of 2D game development by creating five real-world games in a step-by-step manner throughout the course of this book.</p> <p>Starting with a blank scene, you will learn all about the new Unity 2D toolset, which will enable you to bring your scene to life. You will create characters, make them move, create some enemies, and then write code to destroy them. After figuring out all the necessities of creating a game, this book will then assist you in making several different games: games with collision, parallax scrolling, Box2D, and more.</p> <p>By the end of this book, you will not only have created several small games, but you will also have the opportunity to put all your new-found knowledge into creating and deploying a larger, full game.</p>
Table of Contents (17 chapters)
Learning Unity 2D Game Development by Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Randomly spawning enemies


We are now going to add enemies to the game. Let's do this by executing the following steps:

  1. To add the enemy, we download and unzip the DwarfSpriteSheet file from the following URL:

    http://freeartsprites.com/roguelike/

    The Dwarf sprite sheet is shown in the following image:

  2. Slice the sprite sheet and create an enemy GameObject.

  3. Name the GameObject enemy.

  4. Add a Box Collider by going to Add Component | Physics 2D | Box Collider 2D.

  5. Add a Rigidbody 2D component to our enemy GameObject by going to Add Component | Physics 2D | Rigidbody 2D.

  6. Create the enemy idle animation the same way we created the hero idle animation.

  7. We spawn multiple enemies by creating instances of our enemy GameObject.

  8. Add the following lines to our hero script:

    var enemy:Rigidbody2D;
    
    function enemySpawn()
    {
    var enemyInstance:Rigidbody2D;
    
    
      enemyInstance = Instantiate(enemy, Vector3(Random.Range(2, 8),Random.Range(-4, 4),0), Quaternion.Euler(new Vector3(0,0,0)));
      }
  9. Within the start() function's braces...