Gaming in Unity

18. Unity 2D Game - Final Scripts

Presented in alphabetical order:

DamageZone.cs

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

public class DamageZone: MonoBehaviour {
    void OnTriggerStay2D(Collider2D other) {
        SpriteController controller = other.GetComponent < SpriteController > ();

        if (controller != null) {
            if (controller.health < controller.maxHealth) {
                controller.ChangeHealth(-1);
            }
        }
    }
}

EnemyController.cs

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

public class EnemyController: MonoBehaviour {
    public float speed;
    public bool vertical;

    Rigidbody2D rb;

    public float changeTime = 3.0f;
    float timer;
    int direction = 1;

    Animator animator;

    bool walking = true;

    // Start is called before the first frame update
    void Start() {
        rb = GetComponent < Rigidbody2D > ();
        animator = GetComponent < Animator > ();
    }

    void Update() {
        timer -= Time.deltaTime;

        if (timer < 0) {
            timer = changeTime;
            direction = -direction;
        }
    }

    void FixedUpdate() {
        if (!walking) {
            return;
        }

        Vector2 position = rb.position;

        if (vertical) {
            position.y = position.y + Time.deltaTime * speed * direction;
            animator.SetFloat("Move X", 0);
            animator.SetFloat("Move Y", direction);
        } else {
            position.x = position.x + Time.deltaTime * speed * direction;
            animator.SetFloat("Move X", direction);
            animator.SetFloat("Move Y", 0);
        }

        rb.MovePosition(position);
    }

    void OnCollisionEnter2D(Collision2D other) {
        SpriteController player = other.gameObject.GetComponent < SpriteController > ();

        if (player != null) {
            player.ChangeHealth(-1);
        }
    }

    public void Dance() {
        walking = false;
        rb.simulated = false;
        animator.SetTrigger("Dancing");
    }
}

HealthCollectible.cs

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

public class HealthCollectible: MonoBehaviour {
    public AudioClip collectible;

    void OnTriggerEnter2D(Collider2D other) {
        SpriteController controller = other.GetComponent < SpriteController > ();

        if (controller != null) {
            if (controller.health < controller.maxHealth) {
                controller.ChangeHealth(1);
                Destroy(gameObject);

                controller.PlaySound(collectible);
            }
        }
    }
}

HealthUI.cs

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;

public class HealthUI: MonoBehaviour {
    VisualElement HealthBar;
    VisualElement[] Hearts;

    VisualElement nextHeart;

    // Start is called before the first frame update
    void Start() {
        HealthBar = GetComponent < UIDocument > ().rootVisualElement.Q("Container");
        Hearts = HealthBar.Children().ToArray();
    }

    public void StartHealthBar(int currentHealth, int maxHealth) {
        for (int i = maxHealth - 1; i >= currentHealth; i--) {
            Hearts[i].style.visibility = Visibility.Hidden;
        }
    }

    public void AnimateHealthBar(bool increaseHealth) {
        if (increaseHealth) {
            nextHeart = Hearts.Where(x => !x.visible).First();
            nextHeart.style.visibility = Visibility.Visible;
        } else {
            nextHeart = Hearts.Where(x => x.visible).Last();
            nextHeart.style.visibility = Visibility.Hidden;
        }
    }
}

Projectile.cs

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

public class Projectile: MonoBehaviour {
    Rigidbody2D rb;

    // Start is called before the first frame update
    void Awake() {
        rb = GetComponent < Rigidbody2D > ();
    }

    public void Launch(Vector2 direction, float force) {
        rb.AddForce(direction * force);
    }

    void FixedUpdate() {
        if (transform.position.magnitude > 1000f) {
            Destroy(gameObject);
        }
    }

    void OnCollisionEnter2D(Collision2D other) {
        EnemyController e = other.collider.GetComponent < EnemyController > ();

        if (e != null) {
            e.Dance();
        }

        Debug.Log("Projectile collision with" + other.gameObject);
        Destroy(gameObject);
    }
}

SpriteController.cs

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

public class SpriteController: MonoBehaviour {
    public float speed = 3.0f;

    Rigidbody2D rigidbody2d;
    float horizontal;
    float vertical;

    public int maxHealth = 4;
    public int health {
        get {
            return currentHealth;
        }
    }
    int currentHealth;

    HealthUI HealthUI;

    public float timeInvincible = 2.0f;
    bool isInvincible;
    float invincibleTimer;

    public GameObject projectilePrefab;

    Vector2 direction;

    AudioSource audioSource;

    public AudioClip throwClip;
    public AudioClip hitClip;

    // Start is called before the first frame update
    void Start() {
        rigidbody2d = GetComponent < Rigidbody2D > ();
        currentHealth = 2;
        HealthUI = GetComponent < HealthUI > ();
        HealthUI.StartHealthBar(currentHealth, maxHealth);
        audioSource = GetComponent < AudioSource > ();
    }

    // Update is called once per frame
    void Update() {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");

        Vector3 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        direction = (Vector2)((worldMousePos - transform.position));
        direction.Normalize();

        if (horizontal < 0) {
            transform.localScale = new Vector3(0.25f, 0.25f, 0.25f);
        } else if (horizontal > 0) {
            transform.localScale = new Vector3(-0.25f, 0.25f, 0.25f);
        }

        if (isInvincible) {
            invincibleTimer -= Time.deltaTime;
            if (invincibleTimer < 0) {
                isInvincible = false;
            }
        }

        if (Input.GetMouseButtonDown(0)) {
            Launch();
        }
    }

    void FixedUpdate() {
        Vector2 position = rigidbody2d.position;

        position.x = position.x + speed * horizontal * Time.deltaTime;
        position.y = position.y + speed * vertical * Time.deltaTime;

        rigidbody2d.MovePosition(position);
    }

    public void ChangeHealth(int amount) {
        if (amount < 0) {
            if (isInvincible) {
                return;
            }
            isInvincible = true;
            invincibleTimer = timeInvincible;
            HealthUI.AnimateHealthBar(false);
            PlaySound(hitClip);
        } else if (amount > 0) {
            HealthUI.AnimateHealthBar(true);
        }

        currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
        Debug.Log(currentHealth + "/" + maxHealth);
    }

    void Launch() {
        GameObject projectileObject = Instantiate(projectilePrefab, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);

        Projectile projectile = projectileObject.GetComponent < Projectile > ();
        projectile.Launch(direction, 600);
        PlaySound(throwClip);
    }

    public void PlaySound(AudioClip clip) {
        audioSource.PlayOneShot(clip);
    }
}

Created by: David Corish