Newer
Older
BlackoutClient / Assets / Gameplay / Cut.cs
using MiniJSON;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cut : MonoBehaviour
{
    private Item item;
    // Start is called before the first frame update
    public float MaxHealth = 1;
    public float RestorePerSecond = 0.1f;
    private float maxSize = 3;

    public GameObject Bad;
    public GameObject Good;

    void Awake()
    {
        item = GetComponentInChildren<Item>();
        item.OnRemoteUpdated = RemoteUpdated;
        maxSize = Bad.transform.localScale.y;
        health = MaxHealth;
    }

    private void RemoteUpdated()
    {
        float newHealth = 0;
        if (item == null) return;
        if (item.Details.ContainsKey("health"))
        {
            newHealth = item.Details.Key("health", Convert.ToSingle);
        }
        else
        {
            newHealth = MaxHealth;
        }

        float newMaxHealth = 0;
        if (item.Details.ContainsKey("max_health"))
        {
            newMaxHealth = item.Details.Key("max_health", Convert.ToSingle);
        }
        else
        {
            newMaxHealth = MaxHealth;
        }

        if (newHealth != health || newMaxHealth != MaxHealth)
        {
            health = newHealth;
            MaxHealth = newMaxHealth;
            UpdateHealthBar();
        }
    }

    private void UpdateHealthBar()
    {
        Vector3 s = Bad.transform.localScale;
        s.y = (health / MaxHealth) * maxSize;
        Bad.transform.localScale = s;

        Vector3 p = Bad.transform.localPosition;
        p.y = s.y * 0.5f;
        Bad.transform.localPosition = p;

        s = Good.transform.localScale;
        s.y = ((MaxHealth - health) / MaxHealth) * maxSize;
        Good.transform.localScale = s;

        p = Good.transform.localPosition;
        p.y = s.y * 0.5f + (health / MaxHealth) * maxSize;
        Good.transform.localPosition = p;
    }

    void StartLocal()
    {
        item.Details["health"] = health;
        item.Details["max_health"] = MaxHealth;
        item.SendUpdate();
    }

    private float health = 1;

    // Update is called once per frame
    void Update()
    {
        if (item != null && item.IsLocal)
        {
            health = Mathf.Min(MaxHealth, health + RestorePerSecond * Time.deltaTime);
            item.Details["health"] = health;
        }
    }
}