Home > Software design >  How do I reduce integer A when integer B increments?
How do I reduce integer A when integer B increments?

Time:06-24

I am generally pretty new to C# and coding in general. Basically, this is what I have.

public bool TimeLeft;

public void Process()
{
    int B = (int)Game.LocalPlayer.Character.TravelDistanceTo(spawnPoint) * 3; // An integer based on the distance of the character to a Vector3(spawnPoint).

    while (TimeLeft)
    {
        int A = Game.GameTime / 1000; //GameTime is time lapsed in game in milliseconds.
    }
           
}

But this is where my brain fries. Let's assume int B is 150. How would I go about do reduce int B by 1 every time int A increases by 1? This happens within a loop.

I declare int B outside of the loop, and A inside because it needs to update every tick. TimeLeft is set somewhere else.

CodePudding user response:

You have to keep track of the value of A. When you poll A anew you store the value in another variable. Then you can compute the difference and decrease B by this difference. Pseudocode:

int A = ...
int B = ...

while(...)
{
  int A_new = ...
  B -= A_new - A;
}

CodePudding user response:

You need to define the values outside of the loop, inside the loop should only be the processing taking place. (Like Adok has mentioned)

I'd also say that while (true) is not a good practise of a general processing loop, unless you're making sure the whole program is defined within that loop.

Some game studios have a certain "Init" function, and an "Update" function, the init will happen when the game starts up the first time, and update will always be repeated like a loop after the init has been triggered. The benefit of using Update over a personal while loop is that it won't miss out out on other looping functions like Drawing

With understanding the difference between initialising and updating, It would be easier to understand a countdown like this:

In Init:

//defining 2 values to count down, one that decreases, and one that sets the value back to default.
int A = 150;
int Amax = A;

In Update:

if (A > 0) 
{
   A -= 1; //decrease the value if it's not at 0
} 
else
{
    //trigger an activity that happens when A reaches 0

    //reset the timer
    A = Amax;
}
  • Related