Hello All!
As part of my top-down shooter that I'm making I am using a vector to hold data on projectiles. Currently, when I run the game on my netbook in release mode or on my pc in debug mode my game begins to lag a lot when adding projectiles to the vector (aka shooting) and when checking for collisions between projectiles and game entities.
Below is the declaration of the vector in the entity.h:
std::vector<Projectile> projectiles;
Below I have the code for firing the projectiles inside a function within entity.cpp:
reloadTimer.restart();
projectiles.push_back(projectile);
// put a projectile in the back of the vector
projectiles[projectiles.size() - 1].resetProjectile(getXPosition(), getYPosition(), xtar, ytar);
// reset the projectiles position and target
And below is the code for the collision between player projectiles and enemy entities:
for(int i = 0; i < EnemyContainer.size(); i ++){
for(int k = 0; k < player.projectiles.size(); k ++){
if(player.projectiles[k].BBCollision(EnemyContainer[i].getSprite())){
// if the player bullet collides with an enemy
EnemyContainer[i].loseHealth(player.getProjDamage()); // make the enemy lose health
player.projectiles.erase(player.projectiles.begin() + k); // "kill" the projectile
}
}
}
I was wondering if any of you wonderful people could help me once again and give me an idea in how to reduce lag when doing those two things? I have already used vector::reserve() in the constructor of the entity class, so I'm not sure what's the problem. Thank you very much in advance!
It ran fine on the netbook without projectiles being fired, and the netbook could also handle updating the projectiles after they had been added to the vector. The projectile.h code is bellow:
class Projectile : public Drawable
{
protected:
// game related stuff
int damage;
float speed;
// math related stuff
float xdif;
float ydif;
float distance;
public:
Projectile();
Projectile(int Damage, float speed, sf::Texture &Texture, sf::IntRect rect);
~Projectile(void);
void resetProjectile(float xstart, float ystart, float xend, float yend); // reset the projectiles position and distance coords
void update(); // update the projectile
}
I've managed to fix the problem with lag when checking for collisions by changing the projectile vector into a projectile* vector earlier this hour, but it's had no effect on the lag when creating the projectile. I've also noticed that there's no lag when erasing the projectiles. The netbook also had no lag in both of these cases