I am trying to create a new instance of a class each time the function iterates and render it onto the screen. Unfortunately, the second times the code iterates the rand() function gives back the same xPos and yPos integer. I tried to put srand(time(NULL)) in the constructor but I have read its a bad habit to call srand() function multiple times. Does anybody know what causes this behaviour?
Main.cpp
#include <iostream>
#include <SDL.h>
#include <vector>
#include <time.h>
#include "WindowAndRenderer.h"
#include "Entity.h"
int main(int argc, char* args[])
{
srand(time(NULL));
Entity animals;
std::vector <Entity> boids;
for (int i = 0; i < 5; i++)
{
Entity animal;
boids.push_back(animal);
}
WindowRenderer WindowRenderer("natural selection v1.2", 800, 600);
WindowRenderer.loadMedia("include/arrow.bmp");
WindowRenderer.Loop(boids, animals);
WindowRenderer.~WindowRenderer();
return 0;
}
Entity.cpp
#include "Entity.h"
Entity::Entity()
: xPos(rand() % 800), yPos(rand() % 600)
{
dimensions = {xPos, yPos, 8, 8};
}
Entity::~Entity()
{
}
int Entity::getx()
{
return xPos;
}
int Entity::gety()
{
return yPos;
}
SDL_Rect Entity::getDimensions()
{
return dimensions;
}
Loop part in WindowAndRenderer.cpp
while (isRunning)
{
while (SDL_PollEvent(&event) != 0)
{
if (event.type == SDL_QUIT || event.key.keysym.sym == SDLK_ESCAPE)
{
isRunning = false;
}
}
// this is where everything gets updated
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
for (int i = 0; i < boids.size(); i++)
{
SDL_RenderCopy(renderer, tex, NULL, &boids[i].getDimensions());
std::cout << boids[i].getx() << std::endl;
}
SDL_RenderPresent(renderer);
boids.push_back(a);
}
Aucun commentaire:
Enregistrer un commentaire