Logo

Glusoft

Event loop

Now it's time to create an event loop inside the main loop

sf::Clock clock;
while (window.isOpen()) {
	sf::Event event;
	sf::Time timeElapsed = clock.restart();
		
	while (window.pollEvent(event)) {
		if (event.type == sf::Event::Closed)
			window.close();

		if (event.type == sf::Event::KeyPressed)
			if(event.key.code == sf::Keyboard::Escape)
				window.close();
	}

As you can see the only event we catch is the closing event, the player is not moved with events but by checking the state of the state of the keyboard directly.
If we use events to handle the movement, we will obtain a jerky movement because there is a small delay to catch events.
// Move the player
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
	player.setPosition(player.getPosition().x - velPlayer*timeElapsed.asMilliseconds(), 
	player.getPosition().y);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
	player.setPosition(player.getPosition().x + velPlayer*timeElapsed.asMilliseconds(), 
	player.getPosition().y);
}

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
	player.setPosition(player.getPosition().x, player.getPosition().y 
	- velPlayer*timeElapsed.asMilliseconds());
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
	player.setPosition(player.getPosition().x, player.getPosition().y 
	+ velPlayer*timeElapsed.asMilliseconds());
}
I use else if only for the opposite direction, not for the adjacent direction, this allows to make diagonals movements by holding two keys.

Updating the bullets

Each frame we need to update the position of the bullet already created, we simply loop through the whole array and check each bullet.

// Update bullets
for (size_t i = 0; i < totalBullets; i++) {
	if (bullets[i] != NULL) {
		bullets[i]->update(timeElapsed.asMilliseconds());
		sf::Vertex* quad = &vertices[i * 4];
		sf::Sprite *spr = bullets[i]->getSprite();

		quad[0].position = sf::Vector2f(spr->getPosition().x, spr->getPosition().y);
		quad[1].position = sf::Vector2f(spr->getPosition().x + spr->getTextureRect().width, 
		spr->getPosition().y);
		quad[2].position = sf::Vector2f(spr->getPosition().x + spr->getTextureRect().width, 
		spr->getPosition().y + spr->getTextureRect().height);
		quad[3].position = sf::Vector2f(spr->getPosition().x, spr->getPosition().y + 
		spr->getTextureRect().height);
	}
}


<-- Definitions --- Bullets patterns -->

Dark theme