Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Problem with a sprite  (Read 1797 times)

0 Members and 1 Guest are viewing this topic.

Pwishie

  • Newbie
  • *
  • Posts: 6
    • View Profile
    • Email
Problem with a sprite
« on: March 14, 2017, 03:10:52 am »
Fairly new to SFML and I was trying to make a simple 2d shooter without using classes.  So instead I started using arrays, yet I can't get the laser beams/bullets to work right.  Here's all the relevant code

sf::Sprite sLasor[ARRAY_LENGTH];
int lasorCounter = 0;

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && frameCounter > 30){
            lasorCounter++;
            frameCounter = 0;
            sLasor[lasorCounter].setPosition(fArwing.x + 65, fArwing.y);
        }
        if (lasorCounter >= 19){
            lasorCounter = 0;
        }
 if(sLasor[lasorCounter].getPosition().y > 0){
            sLasor[lasorCounter].move(0, -5);
        }
window.draw(sLasor[lasorCounter]);
 

The problem is that every time I press space, the lasers reset and the one I shot earlier just disappears.  If I don't shoot another one the bullet will continue going until it exits the screen. 

Turbine

  • Full Member
  • ***
  • Posts: 100
    • View Profile
Re: Problem with a sprite
« Reply #1 on: March 14, 2017, 03:53:18 am »
You may want to consider using classes to make it simplier, basically you'll need to store a state of the bullet every frame - each bullet having their own position, angle/direction, speed. So you'd add a new bullet class to your array when firing, loop through a fucntion in the bullet every frame to move it and then draw it.

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Problem with a sprite
« Reply #2 on: March 14, 2017, 02:21:40 pm »
I agree with Turbine's solution to use classes. Preferably contained in an STL container such as an std::vector, std::deque, std::list, or std::array.

However, with your code, the problem that you're experiencing is likely due to the fact that you only ever manipulated one laser: sLasor[lasorCounter]. That is regardless of what lasorCounter actual is, you only use the "current" lasorCounter value.
If you have 5 lasers, I would expect lasorCounter to be 5. Therefore, instead of just updating and drawing the fifth laser, you should update and draw all lasers up to the fifth:
for (unsigned int laserNumber{ 0u }; laserNumber < lasorCounter; ++laserNumber)
{
    sf::Sprite& currentLaser{ sLasor[laserNumber] };
    // update and draw "currentLaser"
}
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

 

anything