Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Space Shooter 2D game

1) Add the Background


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.
Set the aspect ratio to 5:4 to match the background image.

2) Add the Spaceship


To control the spaceship so we will need to write some code. Create script “spaceshipScript”
3) Move Script:
Accessing Local Components: Accessing the Transform
The most common component you work with is the transform component. By editing this, you can make objects
move around the screen. Remember that an object’s transform is made up of its translation (or position), its rotation,
and its scale. Although you can modify those directly, it is easier to use some built-in options called the Translate
method, the Rotate method, and the localScale variable:
//Moves the object along the positive x axis.
//The '0f' means 0 as a float (floating point number). It is the way Unity reads floats
transform.Translate(0.05f, 0f, 0f);
//Rotates the object along the z axis
transform.Rotate(0f, 0f, 1f);
//Scales the object to double its size in all directions
transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);

void Update () {
// Move the spaceship when an arrow key is pressed
if (Input.GetKey("right")) // (KeyCode.RightArrow)
{
transform.Translate(0.5f, 0f, 0f);

}
else if (Input.GetKey("left")) // (KeyCode.RightArrow)
{
transform.Translate(-0.5f, 0f, 0f);
}

In order to make spaceship to interact 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.
Using GetComponent
You can interact with components at runtime through scripts. The first thing you must do is “Get” the component
you want to work. The GetComponent<Type>() method has a slightly new syntax, using chevrons to specify the
Type you are looking for (e.g. Light, Camera, and another script name). There are another versions of this method
where you specify the type inside the brackets like a normal parameter, but the version used here is more commonly
used. GetComponent returns the component of the specified type that is attached to the same game object as your
script. E.g. rb2d = GetComponent<Rigidbody2D>();
//Store a reference to the Rigidbody2D component required to use 2D Physics.
private Rigidbody2D rb2d;
//Floating point variable to store & control the player's movement speed
public float speed = 10.0f;
void Start () {
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D>();
}
void Update () {
// Move the spaceship when an arrow key is pressed
if (Input.GetKey("right")) // (KeyCode.RightArrow)
{
// transform.Translate(0.5f, 0f, 0f);

rb2d.velocity = new Vector2(speed, 0f);


}
else if (Input.GetKey("left")) // (KeyCode.RightArrow)
{
rb2d.velocity = new Vector2(-speed, 0f);
}
else
rb2d.velocity = new Vector2(0f,0f);
}

4) Create a Bullet
Add a “rigidbody 2D” component to it, and make sure to check “is Kinematic”.
Create “bulletScript”
public class bullet : MonoBehaviour {
//Floating point variable to store & control the bullet movement speed
public int speed = 6;
//Store a reference to the Rigidbody2D component required to use 2D Physics.
private Rigidbody2D rb2d;

// Use this for initialization


private void Start ()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D>();
rb2d.velocity = new Vector2(0f, speed);
}

private void OnBecameInvisible()


{

Destroy(this.gameObject);
}
}
Since we set the ‘speed’ variable as public, it means that we can directly edit it from the inspector.
Create bullet prefab and delete from scene
A prefab is a special type of asset that bundles up game objects. Unlike simply nesting objects in the Hierarchy view,
a prefab exists in the Project view and can be reused over and over across many scenes. This allows you to generate
a nearly infinite number of objects during runtime. The best part is that any game object, or collection of game
objects, can be put in a prefab
 Prefab: The prefab is the base object. This exists only in the Project view. Think of it as the blueprint.
 Instance: An actual object of the prefab in a scene. If the prefab is a blueprint for a car, an instance is an
actual car. If an object in the Scene view is referred to as a prefab, it is really meant that it is a prefab instance.
The phrase instance of a prefab is synonymous with object of a prefab or even clone of a prefab.
 Instantiate: The process of creating an instance of a prefab. It is a verb and is used like: “I need to instantiate
an instance of this prefab.”
5) Fire Bullets
To make the spaceship fire the bullets we will need to make some changes to our “spaceshipScript”,
// A variable that will contain our bullet prefab
public GameObject bullet;
Add to Update.
// When the spacebar is pressed
if (Input.GetKeyDown(KeyCode.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); //transform.rotation
}

Instantiate(GameObject prefab, Vector3 position, Quaternion rotation);


This method requires three parameters. This method simply reads in a game object variable and makes a new object
of it. The location, rotation, and scale of the new object are the same as the prefab in the Project view.
Quaternions are four dimensional vectors of real numbers used to represent rotations.
Quaternion.identity corresponds to "no rotation" - the object is perfectly aligned with the world or parent axes.

Create reference to bullet in Spaceship Script


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.

6) Create Enemies
Create enemies similar to created bullet.
Add a “rigidbody 2D” component to it, and make sure to check “is Kinematic”.
Create “enemyScript”
// Public variable that contains the speed of the enemy
public int speed = -5;

// Function called when the enemy is created


void Start ()
{
// Get the rigidbody component
rb = GetComponent<Rigidbody2D>();

// Add a vertical speed to the enemy


rb.velocity = new Vector2(0, speed);

// Make the enemy rotate on itself


// r2d.angularVelocity = Random.Range(-200, 200);
}

Void Update()
{
//Rotate the transform of the game object this is attached to by 45 degrees, taking into
account the time elapsed since last frame.
transform.Rotate(new Vector3(0, 0, 45) * Time.deltaTime);
}
Motion must be relative to time. In Unity, the Time class is available for reading and understanding time and its
passing in script. Discuss FrameRate. Framerates are not constant. They change slightly every few frames, even if
there's very little going on in your scene. One frame might load 5% faster than the one before it and the next one
might load 2% slower. This inconsistency leads to jittery looking movement because even though the object might
move the same amount each frame, each frame loads at slightly different speeds.
To fix this, you adjust the amount moved to account for the actual time passed since the last frame loaded. That way
it doesn't really matter if a frame loads slower or faster, because the movement is adjusted to what it should be in
order to look smooth. It's not actually a performance issue, but instead makes movement appear more smooth.
deltaTime is the time it takes from one frame to the next or the time taken the since the Update() function last ran
Delta means the measurement of some value relative to the last measurement taken.

// Function called when the object goes out of the screen


function OnBecameInvisible()
{
// Destroy the enemy
Destroy(gameObject);
}
Create enemy prefab and delete from scene
7) Spawn Enemies
Spawn: Spawning is the process by which a player or entity enters a game.
Spawning point: A spawning point is the place where a player or entity spawns. There can be one or many of these.
They can be stationary or moving around.
We want to randomly spawn enemies on the top of the screen.
Create a new object from where they will appear. Drag the spawn object from the Textures folder
Add a new script to the spawn object called "spawnScript" with this code.

// Variable to store the enemy prefab


public GameObject enemy;

// Variable to know how fast we should create new enemies


public float minSpawnDelay = 1f;
public float maxSpawnDelay = 3f;

// New function to spawn an enemy


void SpawnEnemy()
{
void Spawn()
{
// Create a meteor at a random x position
Vector3 spawnPos = transform.position + new Vector3(Random.Range(-8, 8), 0, 0);

// Create an enemy at the 'spawnPoint' position


Instantiate(enemy, spawnPos, Quaternion.identity);

// Invoke("Spawn", Random.Range (minSpawnDelay, maxSpawnDelay));


}
This script is doing a few interesting things. The first thing is that it is creating two variables to manage the meteor
timing. It also declares a GameObject variable, which will be the meteor prefab. In the Start() method we call the
function Spawn(). This function is responsible for creating and placing the meteors. You can see that the meteor is
spawned at the same y and z coordinate as the spawn point, but the x coordinate is offset by a number between −6
and 6. This is to allow the meteors to spawn across the screen and not always in the same spot. Once the position
for the new meteor is determined, the Spawn() function instantiates (creates) a meteor at that position with no
rotation ( Quaternion.identity ). The last line “invokes” a call to the spawn function again. This method, Invoke() , will
call the named function (in this case Spawn() ) after a random amount of time. That random amount is controlled by
our two timing variables. In the Unity editor, click and drag your meteor prefab from the Project view onto the Meteor
Prefab property of the Meteor Spawn Script component of the meteor spawn object (try saying that fast!). Run the
scene and you should notice meteors spawning across the screen (Attack, my minions!).

Void Start()
{
Spawn();
}

This code basically creates a new enemy every spawnTime seconds somewhere on this white line.

Don't forget to set the public variable by dragging the enemy prefab on the "enemy" input.
Now you can test the game by pressing the play button
8) Handle Collisions
Select the enemy prefab and check the "is trigger" option in the box collider component. This is telling Unity to call
the function OnTriggerEnter2D each time the enemy collides with something.
Now add this new function at the end of the enemyScript.

// Function called when the enemy collides with another object.


//OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
private void OnTriggerEnter2D(Collider2D collision)
{
// Name of the object that collided with the enemy
string name = collision.gameObject.name;

// If the enemy collided with a bullet


if (name == "bullet(Clone)")
{
// Destroy itself (the enemy) and the bullet
Destroy(gameObject);
Destroy(collision.gameObject);
}

// If the enemy collided with the spaceship


if (name == "spaceship")
{
// Destroy the spaceship
Destroy(collision.gameObject);
}
}
The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function.
However, you can also use the physics engine simply to detect when one collider enters the space of another without
creating a collision. A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object
and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call the
OnTriggerEnter function on the trigger object’s scripts.
Finding an object in the scene can be achieved through either the GameObject.Find or
GameObject.FindObjectWithTag function. Of these two, the latter should almost always be preferred for
performance reasons. However, let's consider GameObject.Find first. This function searches the scene for the first
occurrence of an object with an exactly matching name (case-sensitive) and then returns that object. The name that's
searched should match the object name as it appears in the Hierarchy panel. Unfortunately, the function performs
string comparisons to determine the match, so it's a slow and cumbersome option. Besides, it's only truly effective
for objects guaranteed to have unique names, and many times, objects won't have.

9) Load Scene Again


To load scene again, add this in enemyScript.
//add SceneManagement namespace for reloading scene if player (space) destroyed
using UnityEngine.SceneManagement;
// A variable that will contain our spaceship
public GameObject spaceShip;

void Start () {
//Finds a GameObject by name and returns it.
spaceShip = GameObject.Find("spaceship");

}
void Update () {

// To load scene again check if spaceship is destroyed.


if (spaceShip==null) //will return true if spaceship collides with enemy
{
// Debug.Log("Its destroyed");
SceneManager.LoadScene("MainScene");
}
}

You might also like