simple routine

Started by
1 comment, last by phil67rpg 12 years, 6 months ago
I am working on a simple routine that uses opengl and c++.I want to count up to a certain number and then back down and up again in an loop but I dont want to use the while comand. I am using this routine to move a paddle back and forth across the screen in a breakout game. here is some of the code I am working on.

[font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"]void[/font][/font][/font][font="Consolas"][font="Consolas"] loop()

{



[/font][/font][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"]if[/font][/font][/font][font="Consolas"][font="Consolas"](j>-380 && j<380)

{

glRectf(375.0+j,0.0,525.0+j,40.0);

j=j+10;

}



[/font][/font][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"]else[/font][/font][/font][font="Consolas"][font="Consolas"] [/font][/font][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"]if[/font][/font][/font][font="Consolas"][font="Consolas"](k<380 && k>-380)

{

glRectf(375.0+k,0.0,525.0+k,40.0);

k=k-10;

}

[/font][/font][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"]else[/font][/font][/font][font="Consolas"][font="Consolas"] [/font][/font][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"][font="Consolas"][color="#0000ff"]if[/font][/font][/font][font="Consolas"][font="Consolas"](l>-380 && l<380)

{

glRectf(375.0+l,0.0,525.0+l,40.0);

l=l+10;

}

}

[/font][/font][font="Consolas"][font="Consolas"]I have been able to move the paddle back and forth across the screen three times only .[/font][/font]
Advertisement
Does that function define 3 variables (one for each move across the screen?)

You can get this done in about 2 variables: an int and bool.

Set the integer to initial position and bool to represent in which direction the ball is moving (lets say false is to the left and true is to the right).

If we start at initial value of -380 and go all the way to 380 by increments of 10, we can do this:

void loop()
{

direction ? k += 10 : k -= 10;
if(k<(-380))
{
k = -380;
direction = true;
}
else if (k>380)
{
k = 380
direction = false;
}
glRectf(375.0+k, 0.0, 520.0+k, 0.0);

}

making the loop much simpler and it will continue forever (unless I've made a careless mistake). Tada!

EDIT: Oh, I hear that the ternary operator (the ? and : combo) is supposedly "bad habit," so you may choose to express it with if statements rather than the way I wrote it.

Yo dawg, don't even trip.

yeah that worked thanks.

This topic is closed to new replies.

Advertisement