Could somebody explain what is happening here?
I’m not super deep into programming so explain in a monkey language please.
I’m making a std::vector container and i add a sf::RectangleShape object to the vector after clicking a button, then im running through all the elements in a for loop and setting the position for my rectangle and normalizing it, so it travels through the screen instead of just teleporting.
After that im drawing each rectangle in the for loop.
The code looks like it should work to me.
PS. I’m using Visual Studio
#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
// ------------------------------------------------- FUNCTIONS-------------------------------------
//Normalizes the vector for bullets
sf::Vector2f NormalizeVector(sf::Vector2f vector)
{
float magnitude = std::sqrt(vector.x * vector.x + vector.y * vector.y);
sf::Vector2f normalizedVector;
normalizedVector.x = vector.x / magnitude;
normalizedVector.y = vector.y / magnitude;
return normalizedVector;
};
//------------------------------------------------- END OF FUNCTIONS ------------------------------
//------------------------------------------------- BULLETS ---------------------------------------
std::vector<sf::RectangleShape>bullets;
sf::Vector2f direction;
float bulletSpeed = 3.0f;
sf::Vector2f normal;
//------------------------------------------------- END OF BULLETS --------------------------------
//GAME LOOP
while (window.isOpen() == true)
{
//------------------------------------------------- UPDATE ------------------------------------
sf::Event e;
while (window.pollEvent(e))
{
if (e.type == sf::Event::Closed || sf::Event::KeyPressed && e.key.code == sf::Keyboard::Escape)
{
window.close();
}
}
//bullets
if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left))
{
//last bullet
int lb = bullets.size() - 1;
bullets.push_back(sf::RectangleShape(sf::Vector2f(35, 10)));
bullets[lb].setPosition(sf::Vector2f(kevin.getPosition()));
direction = sf::Vector2f(sf::Mouse::getPosition()) - bullets[lb].getPosition();
normal = NormalizeVector(direction);
}
for (size_t i = 0; i < bullets.size(); i++)
{
bullets[i].setPosition(sf::Vector2f (bullets[i].getPosition() + direction * bulletSpeed));
}
//------------------------------------------------- END OF UPDATE -----------------------------
//------------------------------------------------- DRAW --------------------------------------
window.clear(sf::Color::Black);
for (size_t i = 0; i < bullets.size(); i++)
{
window.draw(bullets[i]);
}
window.display();
//------------------------------------------------- END OF DRAW -------------------------------
}}
I tried looking for the possible solutions on the internet, but i am not advanced enough to understand what debug assertions are.
Rogl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.