Hi there. I've run into a bit of a problem using C++ in the sense that I am trying to draw a sprite that will draw itself at a random value between 1 and 600 on the x axis.
However, it seems that using rand() causes the xpos of my sprite to update to a random value on every update, rather than drawing it at a random position from the start, then keeping that value.
I feel I've explained that rather poorly, so a shortened version would be:
How do I get rand() to store a random value rather than updating constantly?
Thanks for any help. Unfortunately it will be hard for me to show you my code as it is spread through many classes.
rand() returns a new random integer everytime it is called. If you'd like to use the same random number over and over, you'll need to save it in your own variable:
In code:
1 2 3
int Tom[10];
for (int i = 0; i < 10; i++)
Tom[i] = rand(); // Copies 10 different random numbers to Tom
1 2 3
int Tom = rand(), Dick[10]; // Tom gets a random number
for (int i = 0; i < 10; i++)
Dick[i] = Tom; // Dick gets the same random number over and over.
In your case, try making the x position, a member of the sprite class. Then set that value with rand() in the constructor (which is done only once). From there on in, only use MySprite.x instead of rand() for that sprite.
The x position is part of a member variable for the Sprite, "m_pos".
However, is there a way for me to get a new random value for m_pos.x each time m_pos.y reaches a certain value?