0

I have created a cube in Visual Studio using C++ and I am trying to give it a random direction to move along. From what I have seen online, the equations I'm using for random numbers should be generating a random number between -1 and 1 or more formally (-1, 1). But for some reason, the random numbers being generated are the exact same.

I feel like there is something wrong with the division but I just cannot figure it out. Any help would be appreciated!

// Give the cube a random direction
float x = 2*((float)rand()/(float)(RAND_MAX + 1.0)) - 1; 
float y = 2*((float)rand()/(float)(RAND_MAX + 1.0)) - 1;
float z = 2*((float)rand()/(float)(RAND_MAX + 1.0)) - 1;

m_directionVector = XMFLOAT3(x, y, z);
Ashot
  • 10,807
  • 14
  • 66
  • 117

2 Answers2

2

you should change seed for new random numbers. use:

srand(time(NULL));
Behnam Safari
  • 2,941
  • 6
  • 27
  • 42
1
    #include <iostream>
    #include <chrono>
    #include <random>

    int main()
    {
        // use current time as a seed
        unsigned nSeed = static_cast<unsigned>
                 (std::chrono::system_clock::now().time_since_epoch().count());

        // choose your favourite random engine
        std::default_random_engine gen(nSeed);

        // chose a distribution: uniform, normal, etc.
        double dLo = -10.0;
        double dHi = 10.0;
        std::uniform_real_distribution<double> dist(dLo, dHi);

        for (int i=0; i<10; ++i)
            std::cout << dist(gen) << std::endl;

        return 0;
    }

.

9.18209
-9.9738
-9.51743
1.78994
4.13958
-2.04672
-9.38406
1.04908
6.23908
2.55983

Note: The above code is pinched (with minor alterations) from http://www.cplusplus.com.

Michael J
  • 7,631
  • 2
  • 24
  • 30