Yajirobe
Yajirobe

Reputation: 115

SFML C++ why is nothing drawn on screen here? (simple code)

Here is my example program using SFML library in C++. I want to create a custom function 'draw_func' which draws something (like a rectangle in this example) at provided coordinates. I set the type of the return variable as an sfml object rectangle (which is what I return and what I draw) but the screen is black.

#include <iostream>
#include <math.h>
#include "SFML/OpenGL.hpp"
#include <SFML/Graphics.hpp>

sf::RectangleShape draw_func(int x, int y)
{
    sf::RectangleShape rect(sf::Vector2f(200, 100));
    rect.setPosition(x, y);
    rect.setFillColor(sf::Color((0, 0, 255)));
    return rect;
}


int main()
{

    int height = 400;
    int length = 400;
    int pos_x = 0;
    int pos_y = 0;

    sf::RenderWindow window(sf::VideoMode(length, height), "My window");

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color::Black);

        sf::RectangleShape rectangle = draw_func(pos_x, pos_y);
        window.draw(rectangle);
        window.display();
    }

}

Upvotes: 1

Views: 208

Answers (1)

Galik
Galik

Reputation: 48605

I think the problem is with this statemen here:

rect.setFillColor(sf::Color((0, 0, 255)));

The double parentheses actually resolves to a single value, 0 because:

sf::Color((0, 0, 255))

constructs a sf::Color with the value 0 because

(0, 0, 255) 

is not function parameters because of the extra parentheses it is an expression involving the comma operator:

0, 0, 255 

The comma operator always has the value of its left most expression. In this case 0.

Now sf::Color has a constructor that takes a single value:

sf::Color(Uint32 color);

You are creating black sf::Color(0).

Upvotes: 4

Related Questions