Skip to content
Snippets Groups Projects
AnimateCircle.cs 2.74 KiB
Newer Older
rchia16's avatar
rchia16 committed
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using TMPro;

public class AnimateCircle : MonoBehaviour
{
    public GameObject block_obj;

    int inhale_period = 0;
    int exhale_period = 0;

    private bool is_inhale; /* 1 if inhalation, 0 if exhaltion */
    private Vector3 scale_diff = new Vector3(0.9f, 0.9f, 0.0f);
    private Vector3 original_scale = new Vector3(0.1f, 0.1f, 0.0f);
    private Vector3 final_scale = new Vector3(0.98f, 0.98f, 0.0f);
    private Vector3 inhale_velocity = new Vector3(0.0f, 0.0f, 0.0f);
    private Vector3 exhale_velocity = new Vector3(0.0f, 0.0f, 0.0f);

    // Start is called before the first frame update
    void Start()
    {
        is_inhale = true;
        original_scale = this.transform.localScale;
        scale_diff = final_scale - original_scale;

        SetPeriod();
        print("scale diff: " + scale_diff);
        inhale_velocity = scale_diff / inhale_period;
        exhale_velocity = scale_diff / exhale_period;
    }

    // Update is called once per frame
    void Update()
    {
        if(is_inhale)
        {
            UpdateInhaleScale();
        }
        else
        {
            UpdateExhaleScale();
        }
        UpdateRespState();
    }

    void SetPeriod()
    {
        string name;
        GameObject go;
        TMP_InputField input_field;
        Transform[] transforms = block_obj.GetComponentsInChildren<Transform>();

        foreach (var transform in transforms)
        {
            go = transform.gameObject;
            name = go.name;
            if (name == "Inhale")
            {
                input_field = go.GetComponent<TMP_InputField>();
                inhale_period = Int32.Parse(input_field.text);
            }
            else if (name == "Exhale")
            {
                input_field = go.GetComponent<TMP_InputField>();
                exhale_period = Int32.Parse(input_field.text);
            }
        }
    }


    void UpdateInhaleScale()
    {
        float dt = Time.deltaTime;
        Vector3 scale = this.transform.localScale;
        this.transform.localScale = inhale_velocity*dt + scale;
    }

    void UpdateExhaleScale()
    {
        float dt = Time.deltaTime;
        Vector3 scale = this.transform.localScale;
        this.transform.localScale = -exhale_velocity*dt + scale;
    }

    void UpdateRespState()
    {
        Vector3 scale = this.transform.localScale;
        if(scale.x >= final_scale.x | scale.x <= original_scale.x)
        {
            if (is_inhale)
            {
                this.transform.localScale = final_scale;
            }
            else
            {
                this.transform.localScale = original_scale;
            }
            is_inhale = !is_inhale;
        }
    }
}