increase and decrease the variable in certain numbers

I have a variable foo = 0 of type float, if I really press the key (E), then the variable increases by 5.0f, if I press the key (Q), then the variable decreases by 5.0f, the question is if the variable foo reaches the number 30, then it can no longer increase, but can only decrease, it can increase only when it does not exceed 30, I can not write it down well in the code, have any ideas?

Just implement exactly what you just wrote. Increase foo, make sure it does not get over 30.

// When you press E:
foo += 5.0f;
if(foo > 30.0f){
    foo = 30.0f;
}

Do the same in reverse for decreasing.
Ideally you will want to save as many of these numbers in easily adjustable class variables.

Technically what you wrote can also be (more closely even) expressed as:

// When you press E:
float fooIncreased = foo + 5.0f;
if(fooIncreased <= 30.0f){
    foo = fooIncreased;
}

I think this is not as readable as the above one. It may also be prone to floating point errors if we used far larger values.

1 Like

What Yoreki said

if(E is pressed) { // pseudo-code obviously
  foo += 5f;
  if(foo > 30f) foo = 30f;
}
if(Q is pressed) {
  foo -= 5f;
  if(foo < 0f) foo = 0f;
}

This can also be expressed as

if(E is pressed) {
  foo = Mathf.Min(30f, foo + 5f);
}
if(Q is pressed) {
  foo = Mathf.Max(0f, foo + 5f);
}

Or you could do an accumulator, instead of acutely reacting to the input/change
which is a better practice because of the separation of concerns

// input and accumulation concern
if(E is pressed) foo += 5f;
if(Q is pressed) foo -= 5f;

// range bounding concern
if(foo < 0f) foo = 0f;
else if(foo > 30f) foo = 30f;

Which can be shortened to

if(E is pressed) foo += 5f;
if(Q is pressed) foo -= 5f;

foo = Mathf.Min(30f, Mathf.Max(0f, foo));

Which is equivalent to a compressed version

if(E is pressed) foo += 5f;
if(Q is pressed) foo -= 5f;

foo = Mathf.Clamp(foo, 0f, 30f);

The last form being an absolute winner in all three categories:

  • readability and maintenance (due to having as little code as possible, and it’s easy to understand)
  • clear separation of concerns (due to making a clear physical distinction between two parts)
  • extensibility without fear of malfunction (due to having the least amount of moving parts, and no redundancy)
1 Like

thank you very much

thank you very much