RenderWindow not working across multiple functions - c++

I'm new to SFML, and have been watching a tutorial that puts everything in a single main function. When making my own program, I tried to split it into multiple functions, but it isn't working properly, can anyone explain why this works:
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
sf::RenderWindow window(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
while (window.isOpen())
{
sf::Event evnt;
while (window.pollEvent(evnt))
{
if (evnt.type == evnt.Closed)
{
window.close();
}
}
window.clear();
window.display();
}
return 0;
}
and this doesn't:
#include <SFML/Graphics.hpp>
#include <iostream>
sf::RenderWindow window;
void setup()
{
sf::RenderWindow window(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
}
int main()
{
setup();
while (window.isOpen())
{
sf::Event evnt;
while (window.pollEvent(evnt))
{
if (evnt.type == evnt.Closed)
{
window.close();
}
}
window.clear();
window.display();
}
return 0;
}
They will both compile and run, but in the former, the window will stay open, and in the latter, it won't.

The window variable that you've declared inside setup() is shadowing the global window. object. Try the following:
void setup()
{
window.create(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
}

Related

SFML: Vector2<double> can't compile

I have this code that I can't compile. It works fine if I replace sf::Vector2<double> with sf::Vector2f. I've tried typedef, but it didn't make any difference.
#include <SFML/Graphics.hpp>
int main() {
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::Vertex line[] =
{
sf::Vertex(sf::Vector2<double>(10.0, 10.0)),
sf::Vertex(sf::Vector2<double>(150.0, 150.0))
};
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
window.clear();
window.draw(line, 2, sf::Lines);
window.display();
}
return 0;
}
The first error:
test.cpp: In function ‘int main()’:
test.cpp:9:47: error: no matching function for call to ‘sf::Vertex::Vertex(sf::Vector2<double>)’
sf::Vertex constructor does not take double vectors, only float vectors. See the documentation.

SFML screen movement is slow

I have recently started to learn SFML and I wanted to make a Pong clone because it should be easy but I got into this problem while coding:
The bat movement is very laggy and when I press A or D it moves a bit then stops then moves again and continues.
#include <SFML/Graphics.hpp>
#include "bat.h"
int main()
{
int windowWidth=1024;
int windowHeight=728;
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML window");
bat Bat(windowWidth/2,windowHeight-20);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
Bat.batMoveLeft();
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
Bat.batMoveRight();
else if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
Bat.batUpdate();
window.draw(Bat.getShape());
window.display();
}
return 0;
}
bat.h
#ifndef BAT_H
#define BAT_H
#include <SFML/Graphics.hpp>
class bat
{
private:
sf::Vector2f position;
float batSpeed = .3f;
sf::RectangleShape batShape;
public:
bat(float startX, float startY);
sf::FloatRect getPosition();
sf::RectangleShape getShape();
void batMoveLeft();
void batMoveRight();
void batUpdate();
};
#endif // BAT_H
bat.cpp
#include "bat.h"
using namespace sf;
bat::bat(float startX,float startY)
{
position.x=startX;
position.y=startY;
batShape.setSize(sf::Vector2f(50,5));
batShape.setPosition(position);
}
FloatRect bat::getPosition()
{
return batShape.getGlobalBounds();
}
RectangleShape bat::getShape()
{
return batShape;
}
void bat::batMoveLeft()
{
position.x -= batSpeed;
}
void bat::batMoveRight()
{
position.x += batSpeed;
}
void bat::batUpdate()
{
batShape.setPosition(position);
}
Your problem is you're input handling strategies (polling events vs. checking current state).
In addition, the way you've implemented this right now, means that if there are – just assumption – 5 events in the queue, you'll move the bat 5 times between drawing. If there is only one event (e.g. "key down"), you'll move the bat once.
What you'll typically want to do is check the events while iterating over them:
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyDown:
switch (event.key.code) {
case sf::Key::Left:
bat.moveLeft();
break;
// other cases here
}
break;
}
}
(Note this is from memory, so untested and might include typos.)

Window not responding while using sockets SFML

I am doing some simple SFML game, and I want to have network communication using udp Sockets. But the problem is that window is blocked and not responding if I try to update position of circle using coordinates that socket receives. Here is the code below. Does anyone know what the problem is?
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <iostream>
#include <string>
#include <iostream>
int posX=100,posY=220,x=5;
sf::UdpSocket receiver;
sf::SocketSelector selector;
void changePosition ();
void defineWindow(sf::RenderWindow &window);
void drawCircle(sf::CircleShape &circle, sf::RenderWindow &window);
int main ()
{
receiver.bind(15000);
selector.add(receiver);
sf::RenderWindow window (sf::VideoMode(800,600), "Krugovi");
defineWindow (window);
return 0;
}
void changePosition ()
{
if (x>0 && posX+x>685) {
posX=685;
x=-x;
}
else if (x<0 && posX+x<15) {
posX=15;
x=-x;
}
else
posX=posX+x;
}
void defineWindow(sf::RenderWindow &window)
{
sf::CircleShape circle(50);
sf::Event event;
sf::Clock clock;
while (window.isOpen()) {
while(window.pollEvent(event)) {
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Escape)
window.close();
}
if (event.type==sf::Event::Closed)
window.close();
}
window.clear(sf::Color::White);
char msg[5];
size_t received;
sf::IpAddress ip;
unsigned short port;
std::string string;
if (selector.wait()) {
if(receiver.receive(msg,sizeof(msg),received,ip,port)==sf::UdpSocket::Done) {
posX=atoi(msg);
}
}
drawCircle(circle,window);
window.display();
}
}
void drawCircle(sf::CircleShape &circle, sf::RenderWindow &window)
{
circle.setFillColor(sf::Color::Yellow);
circle.setOutlineThickness(15);
circle.setOutlineColor(sf::Color::Red);
circle.setPosition(posX,posY);
window.draw(circle);
}
sf::SocketSelector::wait() without any parameters will wait forever until something is received on one of it's sockets, so you won't be responding to events in your window.
If you pass it a time to wait, for example sf::milliseconds(5) then you can continue to poll for events
Relevent docs here

Sfml pollEvent, every new image deletes the previous one

My problem is that the function don't do what I want.
This "CreateWindow" function has the main loop. In the main loop I want a fixed background and, every time I press the H button, I want to draw a Card (sprite) on the background.
What's the problem here? My function draw the cards but when I press H the previous card is deleted and the next card is drawn.
This is something about the event I think, because every time an event happens (I move the mouse, I press an other key etc) the previous card is deleted...
I'm using sfml 2.0
Here is my implementation of the Graphic class
#include "Graphic.h"
#include "SFML/Graphics.hpp"
#include <iostream>
#include <string>
#include "Card.h"
#include <string>
#include <sstream>
Graphic::Graphic(int offset)
{
this->offset = offset;
}
Graphic::~Graphic()
{
//dtor
}
int Graphic::CreateWindow(sf::RenderWindow& window, Deck &deck0)
{
sf::Vector2i screenDimensions(800, 600);
//Dimensioni della window
window.create(sf::VideoMode(screenDimensions.x, screenDimensions.y), "BlackJack", sf::Style::Titlebar | sf::Style::Close);
int index = 0;
window.setKeyRepeatEnabled(false);
//settare il background
sf::Texture bTexture;
sf::Sprite bImage;
if(!bTexture.loadFromFile("Background.png"))
std::cout << "Error" << std::endl;
bImage.setTexture(bTexture);
bImage.setScale(1.0, (float)screenDimensions.y / bTexture.getSize().y);
//MAIN LOOP----------------------
while(window.isOpen())
{
sf::Event Event;
while(window.pollEvent(Event))
{
window.clear();
window.draw(bImage); // this is the function which draw the background
if (Event.type == sf::Event::Closed)
{
window.close();
}
if(Event.key.code == sf::Keyboard::H)
{
Card * y = deck0.dealFirst();
drawCard(window,y->graphNumber,y->getSeed(),offset);
offset = offset + 50;
}
window.display();
}
}
}
int Graphic::drawCard(sf::RenderWindow &window, int graphNumber, string seed, int offset)
{
std::ostringstream oss;
oss << graphNumber << seed << ".png";
std::string var = oss.str();
sf::Texture QHTexture;
sf::Sprite QHImage;
if(!QHTexture.loadFromFile(var))
std::cout<< "Error" <<std::endl;
QHImage.setTexture(QHTexture);
QHImage.setScale(0.5, 0.5);
QHImage.setPosition(offset + 100, 400);
window.draw(QHImage); //this is the function which draw the card's sprite
return 0;
}
Alright you shouldn't be drawing inside of your while(window.pollEvent()) loop, you should be drawing something like this:
while(window.isOpen())
{
sf::Event Event;
while(window.pollEvent(Event))
{
if (Event.type == sf::Event::Closed)
{
window.close();
}
if(Event.key.code == sf::Keyboard::H)
{
Card * y = deck0.dealFirst();
drawCard(window,y->graphNumber,y->getSeed(),offset);
offset = offset + 50;
}
}
window.clear();
window.draw(bImage); // this is the function which draw the background
window.display();
}
The way you were drawing your draw call will only happen if there is an SFML event, and will only ever clear if there is an sfml event(Which is ok if you dont want it to constantly render every frame... and aren't planning any kind of animations...).
So when you hit H an sfml event was being triggers that called your draw card function, however since your card is a local variable to the function you wrote, at the end of the function it is cleared out. You need to store your cards somewhere, such as a vector or list of sf::Sprite. So an example would be:
#include "Graphic.h"
#include "SFML/Graphics.hpp"
#include <iostream>
#include <string>
#include "Card.h"
#include <string>
#include <sstream>
Graphic::Graphic(int offset)
{
this->offset = offset;
}
Graphic::~Graphic()
{
//dtor
}
int Graphic::CreateWindow(sf::RenderWindow& window, Deck &deck0)
{
sf::Vector2i screenDimensions(800, 600);
//Dimensioni della window
window.create(sf::VideoMode(screenDimensions.x, screenDimensions.y), "BlackJack", sf::Style::Titlebar | sf::Style::Close);
int index = 0;
window.setKeyRepeatEnabled(false);
//settare il background
sf::Texture bTexture;
sf::Sprite bImage;
if(!bTexture.loadFromFile("Background.png"))
std::cout << "Error" << std::endl;
bImage.setTexture(bTexture);
bImage.setScale(1.0, (float)screenDimensions.y / bTexture.getSize().y);
//MAIN LOOP----------------------
while(window.isOpen())
{
sf::Event Event;
while(window.pollEvent(Event))
{
if (Event.type == sf::Event::Closed)
{
window.close();
}
if(Event.key.code == sf::Keyboard::H)
{
Card * y = deck0.dealFirst();
drawCard(window,y->graphNumber,y->getSeed(),offset);
offset = offset + 50;
}
}
window.clear();
window.draw(bImage); // this is the function which draw the background
for(int i = 0; i < cardList.size(); ++i)
{
window.draw(cardList[i]);
}
window.display();
}
}
int Graphic::drawCard(sf::RenderWindow &window, int graphNumber, string seed, int offset)
{
std::ostringstream oss;
oss << graphNumber << seed << ".png";
std::string var = oss.str();
sf::Texture QHTexture;
sf::Sprite QHImage;
if(!QHTexture.loadFromFile(var))
std::cout<< "Error" <<std::endl;
QHImage.setTexture(QHTexture);
QHImage.setScale(0.5, 0.5);
QHImage.setPosition(offset + 100, 400);
cardList.push_back(QHImage); //this adds the sprite to our list
return 0;
}

loading texture in SFML with std::future

Visual Studio Express 2012, CTP1 c++ compiler
The following code works. It loads an image and displays it on the window until you close it.
#include <memory>
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800,600), "hello");
auto Load = []() -> std::unique_ptr<sf::Texture> {
std::unique_ptr<sf::Texture> tex_ptr(new sf::Texture);
tex_ptr->loadFromFile("hello.png");
return tex_ptr;
};
auto tex_ptr = Load();
sf::Sprite spr(*tex_ptr);
while (window.isOpen())
{
sf::Event ev;
while (window.pollEvent(ev))
{
if (ev.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(spr);
window.display();
}
}
In the following code, I'm trying to load the image asyncronously using std::async. It prints "load success", which indicates that the load succeeded in the lambda. Then, outside, after I've retrieved the texture from the future, I check other properties of the texture. The size prints out correctly. However, no image shows up. I just get a black window, which closes on command.
#include <future>
#include <memory>
#include <iostream>
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800,600), "hello");
auto Load = []() -> std::unique_ptr<sf::Texture> {
std::unique_ptr<sf::Texture> tex_ptr(new sf::Texture);
if (tex_ptr->loadFromFile("hello.png"))
std::cout << "load success\n";
else
std::cout << "load failure\n";
return tex_ptr;
};
auto tex_ptr_future = std::async(std::launch::async, Load);
auto tex_ptr = tex_ptr_future.get();
sf::Sprite spr(*tex_ptr);
// Oddly, this prints out exactly what I expect
auto size = tex_ptr->getSize();
std::cout << size.x << 'x' << size.y << '\n';
while (window.isOpen())
{
sf::Event ev;
while (window.pollEvent(ev))
{
if (ev.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(spr); // nothin'
window.display();
}
}
Does anybody see anything I'm doing wrong?