Generating random number between -1 to 1 with C++

henrythechief

Distinguished
Aug 15, 2010
1
0
18,510
I'm making a pong game for an assignment in class and what I'm trying to do is when my ball starts, i want it's direction of my ball to be change randomly every time i press space-bar. some reason its keeps generating the same value over and over.
here's my code:

if ((BallXspeed == 0) && (BallYspeed == 0))
{
//restarts ball
if(IsKeyDown(' '))
{
srand ( time(NULL) );
iRandX = (((rand() % 200) / 200 ) * 2) - 1;
iRandY = (((rand() % 200) / 200 ) * 2) - 1;
BallXspeed = 3 * iRandX;
BallYspeed = 3 * iRandY;
}
}

hope i can get some help soon.
thanks.
 

truegenius

Distinguished
Oct 22, 2011
113
0
18,660
your program is complicated to me.

But if it is in c++ then to generate random number in a program you need to initiate randomize() function first then use random.

Example
// program to generate random number from 0 and 99.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{int a=0;
randomize();
a=random(100);
cout<<a;
getch();}

let me know if it was helpful.