Trying to understand "direction = -direction"

Hey all! Hope you are doing well.

I am having a difficult time understanding the math/logic behind

if(AxeY > 450)
{
AxeDirection = -AxeDirection;
}

and why it moves DrawRectangle in the opposite direction.

My initial expectation is that as soon as the box is at 449, it would exit the if statement and just keep adding AxeDirection(originally initialized as 10). Therefore, going back and forth between 440 and 450 until the while loop is closed via WindowShouldClose().

Is it because AxeDirection stays at -10 because the initialization is outside of the while loop and therefore, doesn’t get reinitialized? Would the box get stuck at 440 if AxeDirection was initialized to 10 inside of the while loop? I am confused!

C++Example

You’re correct. Since AxeDirection is initialized outside of the while loop, the if statement that checks the Y-coordinate of the axe is able to invert the movement and the variable stays negative until that condition is met again, where it is inverted once again.

If you put

while (!WindowShouldClose()) {

        int AxeDirection{10}; // axe direction initialized WITHIN the loop

        //...

        AxeY += AxeDirection; // axe position incremented BEFORE condition is checked

        if (AxeY > 450 || AxeY < 0) {

                AxeDirection = -AxeDirection;

        }

        //...

        // execution returns to top of while loop

}

then the axe would actually move off of the bottom of the screen. This is because not only are you re-initalizing AxeDirection to 10 each time the while loop executes, but the movement to the axe (AxeY += AxeDirection) is being done before the if statement is evaluated. So, AxeY is incremented by 10, then the AxeDirection is inverted (if the condition is true), but this new value is never actually used (because the execution returns to the top of the while loop, AxeDirection = 10, repeat).

With the declaration and initialization of AxeDirection outside of the while loop, the AxeDirection is inverted and stays positive or negative, until the if statement is true and it is inverted once again.

image

image

image

Could not have said it better myself, well done!

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms