Day 2 Solutions




Camera Tracker (Locked version)

 
using UnityEngine;

public class CameraTrackerLocked : MonoBehaviour
{
    public Transform target;

    void LateUpdate()
    {
        //add an offset to the target position on the z axis so the camera is pulled back from the character a little bit.
        transform.position = target.position + new Vector3(0,0,10);
    }
}

Camera Tracker (Lerping version)

Lerp is short for “interpolate”. See the Docs on Vector3.Lerp


using UnityEngine;

public class CameraTrackerLerp : MonoBehaviour
{
    public Transform target;
    public float trackSpeed = 10f;

    void LateUpdate()
    {
        //add an offset to the target position so the camera is pulled away from the character a little bit
         Vector3 targetPosition = target.position + new Vector3(0,0,10);

        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * trackSpeed);
    }
}

Teleporter


using UnityEngine;

public class Teleporter : MonoBehaviour
{
    public Transform destination;
    public Vector3 offset;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        collision.transform.position = destination.transform.position + offset;
    }
}


Treasure


using UnityEngine;

public class Treasure : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Inventory inventory = collision.gameObject.GetComponent<Inventory>();
        if (inventory != null)
        {
            inventory.treasure += 1;
            Destroy(this.gameObject);
        }
    }
}


Inventory


using UnityEngine;

public class Inventory : MonoBehaviour
{
    public int treasure;

    public void CollectTreasure(int amount)
    {
        treasure += amount;
        //trigger a sound or an animation here
    }
}


Inventory Display


using UnityEngine;
using UnityEngine.UI;

public class InventoryDisplay : MonoBehaviour
{
    public Inventory inventory;
    public Text treasureDisplay;

    // Update is called once per frame
    void Update()
    {
        treasureDisplay.text = inventory.treasure.ToString();
    }
}