Hi all, I am currently learning C++ with SFML.
For the past few hours I have been stuck on trying to create bullets in my game. I understand what I need to do but I am bit stuck on how to get my objects to draw based on certain conditions. I am trying to do this in an OOP way so I'll do my best to explain and show you what I have done so far.
So I have a weapon class. A weapon has a vector of bullets. I have reserved space at initialization and I load the vector with 100 bullets.
The bullets should only be drawn when they're active. By default they are not and only become active once the player fires using the 'space key'.
Once they are active I also allowed them to be updated so that they can move on the Y axis, I will be implementing enemies and then checking if they collide with anything or go off the screen, if they do so I will set them back to inactive so they can be reused.
I am inheriting from sf::Drawable in the bullet class but I am not sure how to pass through the vector to it so it can check which bullets are to be drawn based on the Boolean. Below is some code in case I didn't make sense!
I also have a texture handler, where I can load in and set textures. However when trying to do this with my Bullet, it only does the first instance and the rest are null. So for now I have created a texture within the bullet class just until I can get it working.
Any guidance/help will be much appreciated, and thanks for taking the time to read my post!
class Bullet : public sf::Drawable , public sf::Transformable
Bullet::Bullet()
: m_Speed(0.1)
, m_isActive(false)
{
m_bulletTexture.loadFromFile("normalBullet.jpg");
m_bulletSprite.setTexture(m_bulletTexture);
m_bulletSprite.setScale(0.1f, 0.1f);
}
void Bullet::Update()
{
if (m_isActive)
{
m_bulletSprite.move(0, 0.1);
}
}
void Bullet::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
if (m_isActive)
{
states.transform *= getTransform();
target.draw(m_bulletSprite, states);
}
}
class Weapon
{
private:
std::vector <Bullet> m_vBullets;
void loadWeapon();
public:
void fireWeapon(); //This is called from the player class when the space bar is hit.
void Weapon::loadWeapon()
{
for (int i = 0; i < 100; i++)
{
m_vBullets.push_back(Bullet());
}
}
void Weapon::fireWeapon() //When the player fires, I want to set the position relative to the players, at the moment for testing purposes I do 50, 50. I then set the bullet to active, as it goes through the vector we keep going until we find a bullet that is not active.
{
for (int i = 0; i < 100; i++)
{
m_vBullets[i].setBulletActive(true);
m_vBullets[i].setBulletPosition(50, 50);
if (m_vBullets[i].isBulletActive() == true)
{
return;
}
}
}