Logo

Glusoft

Main class Bullet

We will need to have a class for the bullet, the class is very short so everything is defined in the header file:

class Bullet {
public:
	Bullet(sf::Texture *tex, sf::Vector2f vel, sf::Vector2f pos, sf::IntRect rect) {
		this->vel = vel;
		spr.setTexture(*tex);
		spr.setTextureRect(rect);
		spr.setPosition(pos);
	}

	// Update the position of the bullet
	void update(double timeElapsed) {
		spr.setPosition(spr.getPosition().x + timeElapsed * vel.x, spr.getPosition().y + 
		timeElapsed * vel.y);
	}

	sf::Sprite* getSprite() {
		return &spr;
	}

private:
	sf::Sprite spr;
	sf::Vector2f vel;
};

For the moment maybe you don't understand the point of having the velocity stored, and what is the parameter double timeElapsed in the function update.
As you can remember from school to calulate the velocity:
velocity of an object = distance / (t2 - t1) and by definition timeElapsed = (t2 - t1) 
=> distance = velocity * timeElapsed

Isn't it more simple to use the distance ?
The distance depend on the timeElapsed and the timeElapsed is variable (by default the framerate is variable). To make the timeElapsed constant we need to enable the vertical synchronization (set the framerate at 60fps).

But in this case we do not want to limit the framerate because we have a lot of bullets to render, so having a very high framerate will allow the program to have a margin to absorb the loss due to the rendering. To sum up the rendering will appear smoother in some cases if the framerate is variable. In the screenshot of the game you can see the framerate is at 326.477295 fps.

<-- Setting up --- Definitions -->

Dark theme