Currently using C 20, GCC 11.1.0
I'm coding for simple movement in a game loop.
Following the abstract pseudocode below, how would I be able to translate this into code? I was thinking of using either goto
to just skip right into the scope that uses the values, or std::optional
to check whether the values exist or not.
The reason I'm trying to do this instead of just adding the bottom if statement into the A...D if statements is because the bottom if statement could become very large, and may add redundancy. Or should I just refactor the if statement into a separate function?
if (direction is left && ...)
{
int xVelocity {left_calculation...};
}
else if (direction is right && ...)
{
int xVelocity {right_calculation...};
}
else if (direction is up && ...)
{
int yVelocity {up_calculation...};
}
else if (direction is down && ...)
{
int yVelocity {down_calculation...};
}
if (x has a value or y has a value)
{
// Do something with those values...
}
CodePudding user response:
When choosing between many options, it's best to use a switch
:
char switch_statement(char x, char y) {
char test_input;
std::cin >> test_input;
switch(test_input) {
case A:
return x;
case B:
return y;
case C:
return x;
case D:
return y;
}
Here is an article that you can read about the differences between a switch
and if
or if else
statements:
https://www.scaler.com/topics/c/difference-between-if-else-and-switch/
CodePudding user response:
You can represent optionality via std::option
:
std::optional xVelocityOpt =
direction == left ? std::make_optional(left_calculation)
: direction == right ? std::make_optional(right_calculation)
: {};
std::optional yVelocityOpt =
direction == up ? std::make_optional(up_calculation)
: direction == down ? std::make_optional(down_calculation)
: {};
if (xVelocityOpt || yVelocityOpt)
{
// you can use the actual values as
// *xVelocityOpt and *yVelocityOpt
// ...
}
... but I'd also consider using simple int
velocities and represent empty as 0
(if what you mean by the variables are delta v in physics).
CodePudding user response:
If instead of x,y you use delta_x,delta_y for relative value change then your problem solves itself. Then your if is just:
int delta_x = 0;
int delta_y = 0;
...
if( delta_x | delta_y )
on_xy_changed(old_x delta_x, old_y delta_y);