How to Make a 2D Space Shooter in Unity - Part 1
Unity is a great framework to build 2D and 3D games. If you don't know why, you should check out my article called discover the power of Unity.
In this tutorial we will see how to make a simple 2D space shooter in Unity and Javascript (Unityscript). This is an introduction to Unity so you just need to have a basic understanding of programming.
Setup
Let’s start by setting up our project. If you don't already have Unity on your computer you can download it for free.
Open Unity and start a new project. Set your project's name and location, and make sure to select “2D” at the bottom.
Now you should see the interface for making 2D games. You can easily change the layout of the interface by moving/resizing the elements. Here’s what mine looks like.
Unity's interface is divided into 6 tabs:
- Scene: a view of the game.
- Game: the live preview of the game.
- Hierarchy: list all the objects currently on the scene.
- Project: shows all the assets of the game: images, sounds, etc.
- Inspector: display information related to the selected object.
- Console: show useful debugging messages.
To keep things organized we are going to create new folders in the project. So go on the project tab and do “Create -> Folder” to create these 4 folders:
- Textures: where we will store all the images.
- Scripts: with all our Javascript code.
- Prefabs: that will contain all our game’s objects.
- Scenes: to store the different scenes of the game.
Now, download this zip file containing all the images for our game. Then drag and drop the images into the Textures folder we just created.
And save your scene by doing "File -> Save Scene". Unity will ask you to name your scene, you can call it “MainScene”. Don’t forget to move the “MainScene” into the Scenes folder.
Add the Background
Drag the background image from the Textures folder to the hierarchy tab.
Select the background in the hierarchy tab. You can see that the inspector tab is now full of interesting information about the background. In this case there are 2 components: transform and sprite renderer.
This is key to Unity: each object has some components attached to it. You can add new components to objects and tweak their values. There are lots of components available, and here's the main ones:
- Transform: to handle the position, rotation and scale of the object.
- Renderer: that contains the sprite displayed.
- Script: a script for this particular object.
- Rigidbody: to add physics: gravity, velocity, etc.
- Colliders: to make the object collide with others.
We'll use all of these in this tutorial.
Add the Spaceship
Drag the spaceship to the hierarchy tab. Since we want our spaceship to move around with the physics engine it needs a “rigidbody”. To do so, go to the inspector and do “Add component -> Physics 2D -> Rigidbody 2D”. Make sure to check “is Kinematic”, otherwise the spaceship would just fall due to gravity.
Change the y position of the spaceship to -4 to put it at the bottom of the screen.
Next, we want to be able to control the spaceship so we will need to write some code. Select the ship, and in the inspector do “Add Component -> New script”. Set the name to “spaceshipScript” and select “Javascript” in the dropdown (in the gif below I select "CSharpt", that's a mistake).
Find the “spaceshipScript” in the project tab and place it inside the Scripts folder. Then double click on the script to open MonoDvelop (Unity's code editor) and replace the default code by this.
// Function called about 60 times per second
function Update() {
// Get the rigidbody component
var r2d = GetComponent("Rigidbody2D");
// Move the spaceship when an arrow key is pressed
if (Input.GetKey("right"))
r2d.velocity.x = 10;
else if (Input.GetKey("left"))
r2d.velocity.x = -10;
else
r2d.velocity.x = 0;
}
Test the Game
Before we test the game you should first go to the game tab and set the aspect ratio to 5:4 to match the background image.
Now we can test the game, and with Unity it’s extremely simple. Just press the play button at the top of the screen and you should be able to move right and left with the arrow keys. Press the play button again to stop the game.
Create a Bullet
Being able to move the spaceship is nice, but it would be better if we could fire some bullets. Let’s do that.
Drag the bullet image from the Textures folder to the hierarchy tab, add a “rigidbody 2D” component to it, and make sure to check “is Kinematic”.
Then add a new script component to the bullet, like we did with the spaceship. Call the script “bulletScript” and put this code in it.
// Public variable
public var speed : int = 6;
// Function called once when the bullet is created
function Start () {
// Get the rigidbody component
var r2d = GetComponent("Rigidbody2D");
// Make the bullet move upward
r2d.velocity.y = speed;
}
// Function called when the object goes out of the screen
function OnBecameInvisible() {
// Destroy the bullet
Destroy(gameObject);
}
Since we set the ‘speed’ variable as public, it means that we can directly edit it from the inspector. That's really handy to quickly tweak the value of a variable without editing any script.
Our bullet is now finished and we need to save it to be able to reuse it. To do so, drag and drop the bullet from the hierarchy tab to the Prefabs folder and then delete the bullet from the scene. Prefabs are an important part of Unity to make your sprite easily reusable.
Fire Bullets
To make the spaceship fire the bullets we will need to make some changes to our “spaceshipScript”. So open it and edit it like this.
// A variable that will contain our bullet prefab
public var bullet : GameObject;
function Update() {
// Move the spaceship horizontally (no changes)
var r2d = GetComponent("Rigidbody2D");
if (Input.GetKey("right"))
r2d.velocity.x = 10;
else if (Input.GetKey("left"))
r2d.velocity.x = -10;
else
r2d.velocity.x = 0;
// When the spacebar is pressed
if (Input.GetKeyDown("space")) {
// Create a new bullet at “transform.position”
// Which is the current position of the ship
// Quaternion.identity = add the bullet with no rotation
Instantiate(bullet, transform.position, Quaternion.identity);
}
}
Notice that:
GetKey()
is true while the key is pressed, whereaseGetKeyDown()
is true only once when the key is pressed. So if you want to fire 2 bullets, you'll have to press the spacebar 2 times.- We don't have to do
GetComponent("Transform")
to get the transform component because unity stores that information directly inside thetransform
variable.
Now we need to tell Unity what our bullet
variable is. Since we made it public you can simply drag the bullet prefab to the spaceship inspector.
And finally, press the play button. You should be able to move and fire bullets.
You can see in the hierarchy tab the bullets being created and deleted from the game.
What’s Next
The Part 1 of this tutorial is over. In Part 2 we will add enemies and handle collisions. Read Part 2.