I am working on a top down 2d shooter game. I have a player Sprite and a Bullet class. I made a vector of pointers to Bullet to store the bullets. Here is the code of the vector and the functions I’m using:
std::vector<std::unique_ptr<Bullet>> b;
while(win.isOpen)
{
//Getting Key Press
if (Keyboard::isKeyPressed(Keyboard::Space))
{
space = true;
}
else
{
space = false;
}
if (space)
{
Bullet b1;
b1.setPos(player.getPosition());
b.push_back(std::make_unique<Bullet>(b1));
}
for (auto& it : b)
{
//Keep Updating
it->update();
}
//Bullet out of Screen
for (int i = 0; i < b.size(); i++)
{
if (b[i]->getPos().y < 0.0f)
{
b.erase(b.begin() + i);
i--;
}
}
//Drawing Bullet
for (auto& i : b)
{
win.draw(i->getSprite());
}
}
The game runs fine but the bullet’s texture won’t load. I’m assuming it has something to do with the vector but I don’t know how to solve it. Here is the Bullet class: Header:
#pragma once
#include <SFML/Graphics.hpp>
using namespace sf;
class Bullet
{
private:
Texture t;
Sprite bullet;
Vector2f pos;
public:
Bullet();
void setPos(Vector2f pos);
void update();
Sprite& getSprite();
Vector2f getPos();
};
Cpp File: #include "pch.h" #include "Bullet.h" #include
Bullet::Bullet()
{
//Setting Texture
if (!t.loadFromFile("Graphics/bullet.png"))
{
std::cout << "Bullet Texture Failed to Load\n";
}
else
{
t.loadFromFile("Graphics/bullet.png");
bullet.setTexture(t);
}
}
void Bullet::setPos(Vector2f pos)
{
//Setting Position
this->pos = pos;
bullet.setPosition(this->pos);
}
void Bullet::update()
{
pos = bullet.getPosition();
bullet.move(0.0f, -4.0f);
}
Sprite& Bullet::getSprite()
{
return bullet;
}
Vector2f Bullet::getPos()
{
return pos;
}