I created an exemple in which i have 2 windows opened at the same time and window1 cant handle events while window2 is open. I changed the current window's color to ilustrate that its working(while window1 is open if i move the mouse, window2 gets greener and greener). But even though window1 cant handle events while window 2 is open, i cant still change window1 position. I want to be unable to do that.
#include <SFML/OpenGL.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
using namespace std;
sf::Event event;
int main()
{
sf::RenderWindow window1(sf::VideoMode(600, 600), "Window1");
sf::RenderWindow window2(sf::VideoMode(300, 300), "Window2");
int r=0,g=0;
while (window1.isOpen())
{
if(window2.isOpen()==false)
while (window1.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window1.close();
r=(r+1)%255;
}
else
{
while (window2.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window2.close();
g=(g+1)%255;
}
}
window1.clear(sf::Color(r,0,0));
window1.display();
window2.clear(sf::Color(0,g,0));
window2.display();
}
return 0;
}
How do i do that?
There isn't direct functionality in SFML for this (although I expect it's possible using platform specific code), but there are a couple of work arounds:
Change the window style to sf::Style::None. This is quick and easy, but has the effect of removing the title bar and window border, which you may not want.
Brute force the window position, either by manually setting the position each render, or checking for a position change and reversing it.
Related
i will make a beat em up game with sfml c++ on mobilephone. So i need to use the Touch function. The problem I have is, what is the best way to detect when the Touch has been pressed, and only execute the code which should be executed when the key has been pressed once? I need it for an animation when the Player make a kick. Now its always repeating the spritesheet animation loop, i wanna fix that, here is the a piece if my code where i need it:
...
if(animHit == true){
if(plrClock.getElapsedTime().asSeconds() > 0.1)
{
animRec.x ++;
if(animRec.x * 103 >= plrtex.getSize().x)
animRec.x = 0;
plrClock.restart();
}
}
FloatRect touchButtonRect = btnSprite.getGlobalBounds();
// the Touch is pressed the button
if(touchButtonRect.contains(worldPos)){
animHit = true;
}
else
{
if(animRec.x * 412<= plrtex.getSize().x){
animHit = false;
}
}
You haven't shown the minimal amount of code needed to replicate the problem, but i think i know where the problem lies. You most likely are trying to get the touch in the while loop without any events. Events are the things that tell your program to run things at, well, a trigger of sorts. This trigger can be a mouse click, resize of window, keyboard buttons or touch events.
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
using namespace std;
using namespace sf;
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
window.setFramerateLimit(60);
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
if(event.type == sf::Event::Closed) window.close();
if (event.type == sf::Event::TouchBegan)
{
//do something
}
if (event.type == sf::Event::TouchEnded)
{
//do something
}
if (event.type == sf::Event::TouchMoved)
{
//do something
}
}
// clear the window with black color
window.clear(sf::Color::Black);
// draw everything here...
// end the current frame
window.display();
}
return 0;
}
With events you can use the triggers really well such as a screen touch. Using touchBegan it will record the single screen touch, even if you hold down the touch it will still be considered single touch.
Hope this helped.
This semester we have to make a game in C++. As a junior in game development in C++ I choosed SFML for graphics (Is that a good choice ? ). All started well, I made my menu and my button and so on. But when I click on this button my window is just closed. And I want to lauch a new window. Anyone can help me ?
Thanks.
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Button.h"
#include "game.h"
using namespace std;
int main() {
sf::RenderWindow window;
sf::Color Color;
sf::Vector2i centerWindow((sf::VideoMode::getDesktopMode().width / 2) - 445, (sf::VideoMode::getDesktopMode().height / 2) - 480);
window.create(sf::VideoMode(900, 900), "SFML Textbox", sf::Style::Titlebar | sf::Style::Close);
window.setPosition(centerWindow);
window.setKeyRepeatEnabled(true);
sf::Font font;
if (!font.loadFromFile("font.ttf"))
std::cout << "Font not found!\n";
//Création de l'image
sf::Texture texture[1];
texture[0].loadFromFile("logo.jpg");
sf::RectangleShape rectangle;
sf::Sprite sprite[1];
rectangle.setSize(sf::Vector2f(750,182));
sprite[0].setTexture(texture[0]);
sprite[0].setPosition(100,50);
//Création du texte
sf::Text text;
text.setFont(font);
text.setCharacterSize(20);
text.setColor(sf::Color(200,0,0));
text.setString("~Made by Théo Manea - 2019/2020 Paris-Sud University~");
text.setStyle(sf::Text::Bold);
text.setPosition(300,850);
//Création du bouton
Button btn1("Jouer", { 200, 100 }, 30, sf::Color::Green, sf::Color::White);
btn1.setFont(font);
btn1.setPosition({ 350, 300 });
//Main Loop:
while (window.isOpen()) {
sf::Event Event;
//Event Loop:
while (window.pollEvent(Event)) {
switch (Event.type) {
case sf::Event::Closed:
window.close();
case sf::Event::MouseMoved:
if (btn1.isMouseOver(window)) {
btn1.setBackColor(sf::Color(200,0,0));
}
else {
btn1.setBackColor(sf::Color(6,164,154));
}
break;
case sf::Event::MouseButtonPressed:
if (btn1.isMouseOver(window)) {
Squadro squadro;
window.close();
}
}
}
window.clear(sf::Color::White);
btn1.drawTo(window);
window.draw(rectangle);
window.draw(sprite[0]);
window.draw(text);
window.display();
}
}
And my game.h :
'''
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
class Squadro{
private:
public:
void Test();
void MainFunctions();
};
void Squadro::Test()
{
cout << "okkkkkkkkkkkkkkkkkkkk" << endl;
}
void Squadro::MainFunctions()
{
sf::Window window(sf::VideoMode(800, 600), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
}
}
#endif // GAME_H_INCLUDED
'''
N.B : I know it's maybe a dumbie question but I need help ! Thanks :D
In general, SFML can be an as good choice for graphics library as can be SDL, Allegro, etc. you just have to use it right (yes, that's the hard part, I know. :)) But that's really subjective, so off-topic here. Let's get to your issue…
The problem is this part:
if (btn1.isMouseOver(window)) { // This is true, if the cursor is over the button
Squadro squadro; // Here you create an object of the other class that shows its own window
window.close(); // now you close the "main" window
} // once you reach this line, "squadro" is destroyed as well, since we're leaving the scope ({...}) it's defined in.
Can this be fixed? Of course. All you have to do is ensure that your Squadro object doesn't get destroyed immediately (plus the outer program code has to ensure it keeps running/updating the Squadro code as well. This can get a bit tricky, so in general I'd recommend sticking to one window only.
Here's the structure I'd use:
For your simple game you should first of all look into two basic concepts:
Main Loop: Have your program run within one main loop (i.e. "while the window is open and the game is running, repeat this"), within which you first process events (such as mouse movement or keyboard presses) and then you update your game and finally draw it.
Finite State Machine: Which allows your game to have different screens or states (but it can also be used for more basic elements such as buttons, enemies, objects, levels, etc.).
A website (and book!) I'd absolutely recommend is Game Programming Patterns. It might be a bit tricky to understand everything at once as a starter, but this website will explain you most important concepts that can make developing your game (of any scale) significantly easier. Just keep in mind the best or most complex approach might be overkill based on the scope and size of your game.
If you want to know more about finite state machines, definitely have a look at their section about it.
Without going too much into details, here's a basic template for a main Game class one might use with SFML (code is simplified/condensed; this is basically what you have already:
class Game {
private:
sf::RenderWindow mWindow;
public:
Game() {
mWindow.create({640, 480}, "My Game");
// Other initialization code
}
~Game() {
// Code to shutdown the game
}
// This is your main game loop
int run() {
while (mWindow.isOpen()) {
handleEvents();
updateGame();
drawGame();
}
return 0;
}
private:
handleEvents() {
// Event handling as you do already
}
updateGame() {
// Update the game
}
drawGame() {
// Draw the game
}
}
In your program's main() you now just have to create an object of the Game class and tell it to run:
int main(int argc, char **argv) {
Game myGame;
return myGame.run();
}
Now to the actual finite state machine. There are many different approaches to this, but the most basic one is just using one variable and an enumeration to identify the current state of the game. Add both to the class:
```cpp
enum GameState {
TitleScreen = 0,
MainGame,
GameOver
} mCurrentState;```
When initializing the game, you set a default state:
```cpp
mCurrentState = TitleScreen;
And now, if you want to switch to a different screen, all you have to do is update this variable, e.g. when the player clicks on a "Start" button:
mCurrentState = MainGame;
The three functions from your main loop, handling events, updating the game, and drawing everything, can then use this variable to determine what to do:
drawGame() {
switch (mCurrentState) {
case TitleScreen:
// Draw the title screen here
break;
case MainGame:
// Draw the actual game here
break;
case GameOver:
// Draw the game over screen here
break;
}
}
In a very similar way, you can give your button it's own internal state as well:
enum ButtonState {
Idle = 0,
Hovered,
Pushed
} mCurrentState;```
So, as the title suggests, I am trying to create a simple Window using SFML 1.6 in CodeBlocks (MinGW v.4.7.0) on Windows 7 (no, I'm not using an ATI GPU).
This is the code:
#include <SFML/Window.hpp>
int main()
{
sf::Window App(sf::VideoMode(800, 600, 16), "SFML Window");
App.Display();
return 0;
}
Whenever I try to run this code, it just says Program.exe is not responding and has to be shutdown using Close this program. The funny thing is, the first tutorial offered on the SFML tutorial website (the one utilizing sf::Clock in a console) works, so the libraries are loaded properly.
Can someone help me find the cause of the error I'm getting?
Other than the crash, I get no compiler or application errors.
The problem is that you haven't created the main loop which polls for events and handles OS messages. Append this to main() (yes, this is a snippet from the SFML documentation):
while (App.IsOpened())
{
// Process events
sf::Event Event;
while (App.GetEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
}
// Clear the screen
App.Clear();
// Put your update and rendering code here...
// Update the window
App.Display();
}
It is therefore not necessary for you to call App.Display() after you create the window.
For those who want the whole thing, this is a snippet extracted from the SFML website.
#include <SFML/Window.hpp>
int main()
{
sf::Window window(sf::VideoMode(800, 600), "SFML Window");
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
}
return 0;
}
You will get:
Well, I tried to do everything as shown in tutorial, but it just shows console and nothing more. Tried this clock program and it works just fine. I connected all libs, and copied all .dll files, so really don't know where I'm wrong. Please tell me what to do to show make it show window. I'm using VS2010, SFML 1.6 and here's my code.
#include <SFML\Window.hpp>
int main()
{
sf::Window App(sf::VideoMode(640, 480, 32), "wut");
while (App.IsOpened())
{
sf::Event Event;
while (App.GetEvent(Event))
{
// Window closed
if (Event.Type == sf::Event::Closed)
App.Close();
// Escape key pressed
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
App.Close();
};
App.Display();
}
};
Try this:
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
int main()
{
// Create the main rendering window
sf::RenderWindow App(sf::VideoMode(800, 600, 32), "SFML Graphics");
// Start game loop
while (App.IsOpened())
{
// Process events
sf::Event Event;
while (App.GetEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
}
// Clear the screen (fill it with black color)
App.Clear();
// Display window contents on screen
App.Display();
}
return EXIT_SUCCESS;
}
Do you link against sfml-main library? If not, try that, if that fails, try to do a WinMain instead of main() function. Also, make sure that Visual Studio has not set your project to a console program.
I have been using SFML a lot recently. Try these suggestions in order, keeping each previous change:
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
It should be sf::RenderWindow, not sf::Window
It should be while (App.isOpen()) not IsOpened()
If it doesnt seem to have the function "isOpen" on your RenderWindow , you probably don't have SFML2, which I recommend getting immediately.
Did you rebuild the libraries for your computer, or did you just try and use the .dll's they provide? You may need to rebuild them using Cmake, and whatever your compiler is. I know I did.
Finally, I also recommend using the latest Code::Blocks as your IDE instead, but I guess only switch as a last resort.
Old question.. but here is my answer: When you sayed; "I'm using VS2010, SFML 1.6...", in the download page says that for sfml-1.6 in Windows, it is possible to use VScode 2005 and VScode 2009. Try to use a different version of Vscode (and link everything to test) and see if it works.
(For me your code looks fine for SFML-1.6, so i don't think that's the problem)
I'm learning the SFML library at the moment but I'm a little lost on moving the sprite. Here's my main.cpp file:
#include <SFML/Graphics.hpp>
int main()
{
// Create the main window
sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");
// Load a sprite to display
sf::Texture Image;
if (!Image.LoadFromFile("cb.bmp"))
return EXIT_FAILURE;
sf::Sprite Sprite(Image);
// Define the spead of the sprite
float spriteSpeed = 10.f;
// Start the game loop
while (App.IsOpened())
{
// Process events
sf::Event Event;
while (App.PollEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Up))
Sprite.Move(spriteSpeed * App.GetFrameTime(), 0);
}
// Clear screen
App.Clear();
// Draw the sprite
App.Draw(Sprite);
// Update the window
App.Display();
}
return EXIT_SUCCESS;
}
But I get really slow, inconsistent movements, why isn't the sprite moving steadily around the screen? Also, seeing as how I plan to use the mouse to control the character how will I use the loop to make the character move towards where the user clicks?
You shouldn't be checking if the key is held down in the event loop.
SFML only posts one event when the key is first pressed down, and then another event when the key is released. In this case, your code is only checking if the key is held when an event occurs (such as moving your mouse, clicking, or anything else).
Moving the IsKeyPressed check out of the event loop, preferably below it, should fix the issue.
Making the sprite move towards your mouse is a more complicated issue, better suited for the Game Development StackExchange.