How to smoothly change a value up and down based on key press?
Hi,
I was wondering if anyone could help me out here. Basically, I have a point light, and I want it to slowly increase in intensity while a button is held down, but then slowly decrease back to 0 once the button is released. I've fiddled around with the Mathf.Lerp function in C#, but I can't seem to get it to work. Anyone have any ideas? Thank you so much to anyone who takes the time to answer. :)
EDIT: I got it to work, but I still have a problem. It smoothly increases while the key is held, and smoothly decreases once it's released, but my problem is that there is a delay of a few seconds between when the key is held down and when the light begins to increase in intensity. Any ideas? Here's my current code.
using UnityEngine;
using System.Collections;
public class LightController : MonoBehaviour {
public Light thrustLight;
public float tParam = 0;
public float lightSpeed = 5.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey ("up")) {
if (tParam < 1) {
tParam += Time.deltaTime * lightSpeed;
thrustLight.GetComponent<Light> ().intensity = Mathf.Lerp (0.1f, 1.8f, tParam);
}
}
else {
tParam -= Time.deltaTime * lightSpeed;
thrustLight.GetComponent<Light> ().intensity = Mathf.Lerp (0.1f, 1.8f, tParam);
}
EDIT AGAIN: I solved it! Because I didn't have an " if (tParam > 0) { }" in my else, the value was going backwards with time, making it delay. Putting that in there makes sure it doesn't go backwards and stays within 0 to 1. Here's my working code for anyone currently trying to google solve this issue:
using UnityEngine;
using System.Collections;
public class LightController : MonoBehaviour {
public int thrustForce = 5;
public Light thrustLight;
public float tParam = 0;
public float lightSpeed = 5.0f;
void Update () {
if (Input.GetKey ("up")) {
if (tParam < 1) {
tParam += Time.deltaTime * lightSpeed;
thrustLight.GetComponent<Light> ().intensity = Mathf.Lerp (0, 1.8f, tParam);
}
}
else {
if (tParam > 0){
tParam -= Time.deltaTime * lightSpeed;
thrustLight.GetComponent<Light> ().intensity = Mathf.Lerp (0, 1.8f, tParam);
}
}
Your answer
Follow this Question
Related Questions
How to fix lighting on spheres made in Blender? 1 Answer
Lighting bakes non-static objects 1 Answer
hi in the scen wive lighting changes not visible and light properety shows me it how fix it ? 0 Answers
2D shader / lighting like Terraria or Starbound 2 Answers
how can I set Lightmap Scale per object 0 Answers