This isn’t related to any specific course content, but I have created my own practice project to work on a little bit (a ring toss game).
I’ve run into a confusing thing and just want to know why it happens. I have a power meter to determine how much force is applied to the ring in order to toss it at the pegs. At the moment it’s just some text ranging from 1%-100% (14-1400 force), but I’m in the process of reworking it to confine it to 80%-100% (1120-1400 force) while still displaying as 1%-100%.
I used a few if statements to keep it in the 80-100 range, but found that it would get stuck at 80% when I used “if (currentPower < powerMax * 0.8f) {currentPower = powerMax * 0.8f;}”. I used “powerMax * 0.8f” instead of a variable because I figured I would only use it in that single method (other than to set the starting power) and didn’t want another power related variable.
After quite a while of scratching my head wondering why it wasn’t working I eventually made a variable and set it to 'powerMax * 0.8f" to make “if (currentPower < testingNumberThing) {currentPower = testingNumberThing}” and the code worked exactly as intended.
Now, to my limited knowledge these two codes were one and the same, so can someone educate me as to why they aren’t?
Here’s the broken code:
float powerMax;
float currentPower;
void Start()
{
powerMax = 1400f
currentPower = powerMax * 0.8f;
}
void ChangePower(float increment)
{
if (currentPower > powerMax)
{currentPower = powerMax;}
else if (currentPower < powerMax * 0.8f)
{currentPower = powerMax * 0.8f;}
else if (currentPower >= powerMax * 0.8f && currentPower <= powerMax)
{currentPower += increment * Time.deltaTime;}
}
here’s the working code:
float powerMax;
float testingNumberThing;
float currentPower;
void Start()
{
powerMax = 1400f
testingNumberThing = powerMax * 0.8f;
currentPower = testingNumberThing;
}
void ChangePower(float increment)
{
if (currentPower > powerMax)
{currentPower = powerMax;}
else if (currentPower < testingNumberThing)
{currentPower = testingNumberThing;}
else if (currentPower >= testingNumberThing && currentPower <= powerMax)
{currentPower += increment * Time.deltaTime;}
}