Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace object every 200 frames

Tags:

c++

Beginner question so bear with me. How could I make this loop so every 200 frames the pine gets swapped with the tree?

int counter;

void swap(void) {
cout << counter++ << endl;
if (counter <= 200)
    drawPine(0, 0);
else
    drawTree(0, 0);
}
like image 528
Ian Copenhaver Avatar asked Jul 10 '26 02:07

Ian Copenhaver


2 Answers

void swap() {
  static int counter = 0;
  if (counter % 400 < 200) {
    drawPine(0, 0);
  } else {
    drawTree(0, 0);
  }
  counter++;
}
like image 69
Indiana Kernick Avatar answered Jul 11 '26 19:07

Indiana Kernick


int counter;

void swap(void) {
    cout << counter << endl;

    counter = (1 + counter) % 400;    
    if (counter < 200)
        drawPine(0, 0);
    else
        drawTree(0, 0);
}

Or, to avoid all the overflow silliness in the comments:

unsigned int counter;

void swap(void) {

    cout << counter++ << endl;

    if (counter % 512 < 256)
        drawPine(0, 0);
    else
        drawTree(0, 0);
}

Changing the flip interval to a power of 2 doesn't prevent the overflow that'll happen in 1.135... years when counter overflows int, but, since the new interval is a factor of INT_MAX, the system will continue to function correctly. Note that some embedded systems will trigger an interrupt when an overflow flag is set, and some of those will jmp to the reset vector. So, if you're running this on an HC11 in 1988, there might be a problem.

like image 37
3Dave Avatar answered Jul 11 '26 19:07

3Dave