2D UFO

Table of Contents

Introduction to 2D UFO Project

Setting Up The Play Field

The layer at bottom(Player, in this case) are rendered last

Controlling the Player

Keep the file name and class name consistent.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed;

    private Rigidbody2D rb2d;

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D> ();
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");
        Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
        rb2d.AddForce (movement * speed);
    }
}

Adding Collision

Box colliders we added overlap each other, but doesn't collide because they don't have any riigd body.

Following the Player with the Camera

While the Player Game Object rotates, the Camera Object, a child of Player, also rotates.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

    public GameObject player;
    private Vector3 offset;

    void Start ()
    {
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate ()
    {
        transform.position = player.transform.position + offset;
    }
}

Creating Collectable Objects

https://docs.unity3d.com/ScriptReference/Transform.Rotate.html

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rotator : MonoBehaviour {

    void Update () {
        transform.Rotate (new Vector3 (0, 0, 45) * Time.deltaTime);     
    }
}

Picking Up Collectables

void OnTriggerEnter2D(Collider2D other) 
{
          if (other.gameObject.CompareTag ("PickUp"))
          {
        other.gameObject.SetActive (false);
          }
}

Counting Collectables and Displaying Score

using UnityEngine.UI;

public Text countText;

void SetCountText()
{
    countText.text = "Count: " + count.ToString ();
}

Building our 2D UFO Game