Temperature system in Unity using c#

1.9k Views Asked by At

I would like my script to add to the temperature when the player sprints (shift) and to subtract when he doesn't. The temperature must not be below what it was (before when he started sprinting), nor above a certain point. I can't just use if higher than x or lower than x because sprinting isn't all that influences it...

Hope I'm not explaining poorly... I thought it would work? What am I doing wrong?

Here is the code:

float tempTime;
public int temperature = 32;

    if (Input.GetKeyDown(KeyCode.LeftShift) && temperature == originalTemp)
        originalTemp = temperature;

    if (Input.GetKeyUp(KeyCode.LeftShift) && Input.GetKeyUp(KeyCode.W) && temperature == originalTemp)
        originalTemp = temperature;

    if (Input.GetKey(KeyCode.LeftShift))
    {
        if (tempTime >= 5f && temperature <= originalTemp * 1.25f && temperature >= originalTemp)
        {
            temperature++;
            tempTime = 0;
        } else {
            tempTime += Time.deltaTime;
        }
    } else if (!Input.GetKey(KeyCode.W)) {
        if (tempTime >= 5f && temperature <= originalTemp * 1.25f && temperature >= originalTemp)
        {
            temperature--;
            tempTime = 0;
        } else {
            tempTime += Time.deltaTime;
        }
    }
1

There are 1 best solutions below

0
On BEST ANSWER

Instead of a tempTime to keep track of how long you're sprinting, you should increase or decrease temperature in an amount proportional to Time.deltaTime, based on whether you are or are not sprinting. This temperature should be kept within the min and max temperature bounds you define.

Also, your originalTemp = temperature lines/if statements are useless as-is, because you only do the set if the values are already equal. You shouldn't need to know the original anyway, just the min (resting) and max (overheating) temperatures.

This should get you on the right track:

public float minTemperature = 32;
public float temperature = 32;
public float maxTemperature = 105;
// this defines both heatup and cooldown speeds; this is 30 units per second
// you could separate these speeds if you prefer
public float temperatureFactor = 30;
public bool overheating;
void Update()
{
    float tempChange = Time.deltaTime * temperatureFactor;
    if (Input.GetKey(KeyCode.LeftShift) && !overheating)
    {
        temperature = Math.Min(maxTemperature, temperature + tempChange);
        if (temperature == maxTemperature)
        {
            overheating = true;
            // overheating, no sprinting allowed until you cool down
            // you don't have to have this in your app, just an example
        }
    } else if (!Input.GetKey(KeyCode.W)) {
        temperature = Math.Max(minTemperature, temperature - tempChange);
        if (temperature == minTemperature)
        {
            overheating = false;
        }
    }
}