count from 0 to 255 and then from 255 to 0

Hello
I have a problem and i have been trying to solve it but i can't.
I have a game while loop and i have a varible called time which is set to 0. I want this variable to increment till 255 and when it reach that number i want it to decrement to 0, and keep incrementing and decrementing forever.

here is what i have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

int Time = 0;
bool disable = false;
while(Game.IsRunning())
{
	if(Time >= 0)
		{
			Time ++;
			if(Time >= 255)
				disable = true;
		}
	
		if(Time >= 255 || disable == true)
		{
			Time --;
		}

		if(Time == 0 )
		{
			Time ++;
			disable = false;
		}

		std::cout<<Time<<"\n";
}
Last edited on
closed account (D80DSL3A)
This may work:
1
2
3
4
5
6
7
8
9
10
int Time = 0;
bool up = true;

if( up )
    ++Time;
else
    --Time;

if( Time == 255 ) up = false;
if( Time == 0 ) up = true;


I'm also using this in a game to modulate the color of some text.
Last edited on
@fun2code
your code isn't working :(
the problem with your code is that its starting from -1 till - 100000.

this problem is so frustrating and i can't figure this out at all.
Well then try:

1
2
3
4
5
6
7
8
9
10
int Time = 0;
bool up = true;

if( up )
    ++Time;
else
    --Time;

if( Time >= 255 ) up = false;
if( Time <= 0 ) up = true;
Last edited on
closed account (D80DSL3A)
Did you assign up = false initially? It must be bool up = true; or that problem would occur.

EDIT: lines 1 and 2 should be outside the while loop and lines 3-10 inside.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int Time = 0;
bool up = true;
while(Game.IsRunning())
{
    if( up )
        ++Time;
    else
        --Time;

    if( Time >= 255 ) up = false;// added inequalities as safeguard against passing over limit value.
    else if( Time <= 0 ) up = true;// more efficient

    std::cout<<Time<<"\n";
}
Last edited on
@Stewbond
thank you so much that workes perfectly.

@fun2code
opps how stupid of me. i forgot to do this bool up = true;.

so both codes work xD thank you guys
Topic archived. No new replies allowed.