-1

My code is here:

As stated above, I'm trying to draw a series of bars across the screen with different x positions and I've stored them in arrays. It seems the code only draws 1 rectangle, even though I've checked and each bar has a different x position so I'm sure its an issue with how I'm drawing the objects but it feels right. I've also made a similar program with vectors using the same loop for drawing but with .at(i) instead which does work but this oddly does not.

I've been trying to figure this out for a while and I'm tired now so please help, point out my errors... etc...

#include <SFML/Graphics.hpp>


int main()
{
    sf::RenderWindow window(sf::VideoMode(640, 640), "Square", sf::Style::Close | sf::Style::Resize);
    sf::RectangleShape bar[64] = {sf::RectangleShape(sf::Vector2f( (window.getSize().x)/64.0f ,100.0f))};
// creates 64 bars of equal width 

    for (int i = 0; i < 64; i++) 
    {
        bar[i].setFillColor(sf::Color(0, 0, 255, 255));
        bar[i].setPosition( 10*i , (window.getSize().y)/2);
// sets bars x position to shift over for every bar
    }
    bar[3].setPosition(600, 300);
    // just a test doesn't render even though it should
    while (window.isOpen())
    {
//////////////////////////////////////////////////
        window.clear(sf::Color(130, 130, 150, 255));
        for (int i = 0; i < 64; i++)
        {
            window.draw(bar[i]);
        }
        window.display();
/////////////////////////////////////////////////
    }```



I cut out the rest of the code as the rest works and really has nothing to do with the code for simplicity sake
I want it to render out rectangles across the screen but it only displays one and I can't figure out why?



  • Please see [how to debug small programs](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Tom Oct 09 '19 at 07:36

1 Answers1

0

sf::RectangleShape has default ctor:

sf::RectangleShape::RectangleShape  (   const Vector2f &    size = Vector2f(0, 0)   )   

You have defined rectangle's size only for the first one, other 63 have default size (0,0).

You can copy/paste your rect definition in raw array, or use std::vector and call ctor which takes value and number of elements:

std::vector<sf::RectangleShape> bars( 64, // num of elems 
      sf::RectangleShape( sf::Vector2f(window.getSize().x/64.0f ,100.0f) ) );

Another solution is to call setSize in every iteration of loop (just like with setFillColor, setPosition etc).

rafix07
  • 20,001
  • 3
  • 20
  • 33