mardi 18 juillet 2017

How to get a different random number in c++ with each class initialization

I have an enemy class called Slime and each slime travels down the path (like a tower defense game) and I'm trying to get a random number (which will tell the slime when to change directions for the path change). But I tried it with using 3 Slimes and they all end up with the same random numbers. My enemy class has this code in it to generate random numbers for x and y:

Enemy::Enemy(Level* level, float x, float y, float speed, int direction, int width, int height)
    :
    Entity(level, x, y, width, height), // Each enemy is an entity
    speed(speed),
    direction(direction)
{
    srand((unsigned)time(0));

    rangeX = (level->GetTileWidth() * level->GetScale() - width * level->GetScale()) - (width * level->GetScale()) + 1;
    rangeY = (level->GetTileHeight() * level->GetScale() - height * level->GetScale()) - (height * level->GetScale()) + 1;

    randNumX = (rand() % rangeX) + (width * level->GetScale());
    randNumY = (rand() % rangeY) + (height * leel->GetScale());
}

That code is being called whenever I create a new Slime object. I'm testing with three different slimes and they all give me the same random numbers. When I restart it, they're different numbers than the original, but all three slimes still have that same random numbers. Am I doing something wrong? Should I be seeding the rand outside of this class so it's only called once? And the rangeX and rangeY just give me a number within the path so no enemy is on the grass or hanging off the path.




Aucun commentaire:

Enregistrer un commentaire