Well, it's interesting and really bad code. I would not emulate this if that's your intention.
All in all, this code is trying to randomly set the position of m_Pos
and randomly setting it's velocity m_Vel
. I assume this would be used for spawning asteroids or other enemies. The only relation it has to movement (as you mention in your title) is the velocities set. There's nothing here that updates position based on velocity or anything like that, so I wouldn't call it movement code.
I'll go through the code line by line.
float r = (float)rand()/(float)RAND_MAX;
Is not used in the code you provided. However, the equation (float)rand()/(float)RAND_MAX
is used a lot, and you should know that this produces a float between 0 and 1. References rand() and RAND_MAX.
if ((float)rand()/(float)RAND_MAX < 0.5) {
m_Pos.x = -app::getWindowWidth() / 2;
We'll call this case A. If (float)rand()/(float)RAND_MAX
is less than .5
set the x
position to negative half the window width (off screen I guess?)
if ((float)rand()/(float)RAND_MAX < 0.5)
m_Pos.x = app::getWindowWidth() / 2;
Unless a second take on random is less than .5
, then set the x
position to the center of the screen.
m_Pos.y = (int) ((float)rand()/(float)RAND_MAX * app::getWindowWidth());
Set the y
position to some random position using the window width. Odd.
else {
m_Pos.x = (int) ((float)rand()/(float)RAND_MAX * app::getWindowWidth());
m_Pos.y = -app::getWindowHeight() / 2;
if (rand() < 0.5)
m_Pos.y = app::getWindowHeight() / 2;
}
The else for case A. Set the x
position randomly in the width of the window. Then set the y
to half way off screen or half way on screen depending on (rand() < 0.5)
(Which no longer divides by RAND_MAX
like everywhere else, for an unknown reason. Meaning this is unlikely to result in a value less than .5
.)
m_Vel.x = (float)rand()/(float)RAND_MAX * 2;
Set the x
velocity randomly.
if ((float)rand()/(float)RAND_MAX < 0.5)
{
m_Vel.x = -m_Vel.x;
m_Vel.y =(float)rand()/(float)RAND_MAX * 2;
}
Again, if (float)rand()/(float)RAND_MAX
is less than .5
, here negate the x velocity you were using before and set the y
velocity to some positive random value.
if ((float)rand()/(float)RAND_MAX < 0.5)
m_Vel.y = -m_Vel.y;
Finally, negate the y
velocity if our random value is less than .5
.