Search code examples
c#unity-game-enginegoogle-cardboardlerp

Lerping Color using Event Trigger SetGazedAt in Unity


I'm using the cardboard sdk and I'm trying to lerp the color of an object when it is gazed at using the cardboard sdk for Unity. I'm using the lerping script below and it functions independently of the gaze when I attach it to the object, but it doesn't work when I try to make a version of it work inside of SetGazedAt.

Below is the code for SetGazedAt that changes a color of the object. How would I replace this or call the Lerp script that I have, which I have titled fill?

Fill.cs

using UnityEngine;
using System.Collections;

public class Fill : MonoBehaviour {

float lerpTime = 2f;
float currentLerpTime;

//float moveDistance = 5f;



Color startColor = Color.clear;
Color endColor = Color.clear;



public void Start() {
    startColor = Color.clear;
    //endColor = new Color(0.0f,0.0f,1.0f,0.5f);
}

public void Update() {



    //reset when we press spacebar
    if (Input.GetKeyDown(KeyCode.Space)) {
        currentLerpTime = 0f;
        startColor = Color.clear;
        endColor = new Color(0.0f,0.0f,1.0f,0.5f);
    }

    //increment timer once per frame
    currentLerpTime += Time.deltaTime;
    if (currentLerpTime > lerpTime) {
        currentLerpTime = lerpTime;
    }

    //lerp!
    float perc = currentLerpTime / lerpTime;
    GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, perc);
}

}

SetGazedAt Method in Teleport script

public void SetGazedAt(bool gazedAt) { 


    GetComponent<Renderer>().material.color = gazedAt ? Color.clear : Color.red;


}

Solution

  • I have figured it out with help from @piojo. I used Coroutines to take care of the lerping update and dropped the fill script. I'm now just calling the FillObject function in my larger teleport script.

    public void SetGazedAt(bool gazedAt) { 
            if (gazedAt == true) {
                aniTrigger = true;
                startColor = Color.clear;
                endColor = new Color(0.0f,0.0f,1.0f,0.8f);
                StartCoroutine(FillObject (startColor,endColor, 3 ));
                //GetComponent<Renderer>().material.color = Color.blue;
            } else {
                GetComponent<Renderer>().material.color = Color.clear;
            }
    
    
        }
    

    and this for the lerp function

    IEnumerator FillObject(Color startColor, Color endColor, float overTime)
        {
            float startTime = Time.time;
            while(Time.time < startTime + overTime)
            {
                //transform.position = Vector3.Lerp(source, target, (Time.time - startTime)/overTime);
                GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, (Time.time - startTime)/overTime);
                yield return null;
            }
            GetComponent<Renderer> ().material.color = endColor;
            var x = this.gameObject.name;
            TeleportNow (x);
    
        }