c++randomogre

rand() returns the same value, even after a srand


I am trying to get a random value, but that doesn't work.

I use this for exemple.

  srand(time(NULL) ^ getpid());

  int a = rand() % 100;

I get a random value the first time, but every other time I call rand(), I get the same value.

My full code :

Worms::Worms(std::string const& name, Ogre::SceneManager *scene,
  Ogre::ColourValue &color, unsigned char hp) :
  _name(name), _hp(hp), _scene(scene), _color(color)
{
  srand(time(NULL) ^ getpid());
  std::cout << "creating worms" << name << std::endl;
  std::cout << color << std::endl;
  this->_ent = scene->createEntity(name, "Worm.mesh");
  this->generatePosition();
  this->setColor(color);
}

void                            Worms::generatePosition()
{
  int a = rand() % 10;
  std::cout << a << std::endl;
  Ogre::Vector3 pos(rand() % 800 + 100 , 450, 0);
  std::cout << pos << std::endl;
  this->_node = this->_scene->getRootSceneNode()->createChildSceneNode(this->_name);
  this->_node->attachObject(this->_ent);
  this->_node->showBoundingBox(true);
  this->_node->scale(_node->getScale() * 4);
  _node->rotate(Ogre::Vector3::UNIT_X, Ogre::Degree(90));
  _node->rotate(Ogre::Vector3::UNIT_Z, Ogre::Degree(90));
  _node->setPosition(pos);
}

And the output :

4
Vector3(498, 450, 0)
creating worms K04L4_1
creating wormsK04L4_1 Captain_2
ColourValue(1, 0, 0, 0)
4
Vector3(498, 450, 0)
creating worms K04L4_1
creating wormsK04L4_1 Captain_3
ColourValue(1, 0, 0, 0)
4
Vector3(498, 450, 0)
creating worms K04L4_1
ok
creating wormsOP3X_2 Pride_1
ColourValue(0, 1, 0, 0)
4
Vector3(498, 450, 0)
creating worms OP3X_2
creating wormsOP3X_2 Captain_2
ColourValue(0, 1, 0, 0)

Solution

  • I was using srand() more than one time in my program, now I call it once in my main() function and that works fine.