Another challenge solution of looping through the hazards with for loop

To not use the magic numbers when iterating array, we can initialize the array using standard c++ library.

First we need to include the array on top of the file:

#include <array>

When initializing the array we need to reference it a little bit differently when choosing this approach:

std::array<AnimData, 5> nebulae;

This creates an array of 5 elements of type AnimData called nebulae.

And then we can get the size of the array in for loops like this:

for (int i = 0; i < (int)nebulae.size(); i++)

Notice that I have casted the size of nebulae to integers, because the function returns type long which is a lot bigger number type compared to integer.

And when we will initialize the different positions of nebulae, we can use a new for loop instead of adding those manually. EDIT: Just went through the next video where this will be a bonus challenge, so don’t check this if you haven’t watched it!

nebulae[0].pos.x = windowDimensions[0];

// index i starts at 1 this time!
for (int i = 1; i < (int)nebulae.size(); i++)
{
  nebulae[i].pos.x = nebulae[i - 1].pos.x + 300;
}

Here I’ll get the previous nebula’s position decrementing the index value by 1.

Privacy & Terms