Professional Documents
Culture Documents
Space Shooter 2D Game: 1) Add The Background
Space Shooter 2D Game: 1) Add The Background
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);
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;
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
}
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;
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.
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.
void Start () {
//Finds a GameObject by name and returns it.
spaceShip = GameObject.Find("spaceship");
}
void Update () {