SFML C++. Bouncing ball with showing coordinates

Published June 16, 2020
Advertisement

l use MinGW and lightweight editor VSCode: https://code.visualstudio.com/docs/languages/cpp

Type the command: mingw32-make

Makefile

# -mwindows - without a console window

CC = g++

INC = -I"E:\Libs\SFML-2.5.1-windows-gcc-7.3.0-mingw-32-bit\include"

LIB = -L"E:\Libs\SFML-2.5.1-windows-gcc-7.3.0-mingw-32-bit\lib"

all: main.o
	$(CC) -mwindows main.o $(LIB) -lsfml-system -lsfml-window -lsfml-graphics -o app

main.o: main.cpp
	$(CC) -c $(INC) main.cpp

main.cpp

#include <iostream>
#include <sstream>
#include <SFML/Graphics.hpp>

template <typename T>
std::string to_string_with_presision(const T a_value, const int n = 1)
{
    std::ostringstream out;
    out.precision(n);
    out << std::fixed << a_value;
    return out.str();
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(280, 280), L"Отскоки круга");
 
    sf::CircleShape disk(20.f);
    disk.setFillColor(sf::Color::Green);
    disk.setOrigin(20, 20);
    
    sf::Font font;
    if (!font.loadFromFile("C:/Windows/Fonts/arial.ttf"))
    {
        std::cout << "Failed to load the font file.";
        return EXIT_FAILURE;
    }

    sf::Text text;
    text.setFont(font);
    text.setCharacterSize(24);
    text.setFillColor(sf::Color::Red);
    text.setStyle(sf::Text::Bold);
    text.setString("(000.0, 000.0)");
    float textWidth = text.getLocalBounds().width;
    float textHeight = text.getLocalBounds().height;
    text.setOrigin(textWidth / 2, textHeight / 2);
 
    float x = 50;
    float y = 150;
    float x_speed = 0.1f;
    float y_speed = 0.1f;
 
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        x += x_speed;
        y += y_speed;
        if (x < 0 + disk.getRadius() || window.getSize().x - disk.getRadius() < x)
        {
            x_speed *= -1;
        }

        if (y < 0 + disk.getRadius() || window.getSize().y - disk.getRadius() < y)
        {
            y_speed *= -1;
        }

        disk.setPosition(x, y);
        text.setPosition(x, y - disk.getRadius() - textHeight);
        text.setString("(" + to_string_with_presision(x) + ", " + to_string_with_presision(y) + ")");
 
        window.clear(sf::Color::White);
        window.draw(disk);
        window.draw(text);
        window.display();
    }
 
    return EXIT_SUCCESS;
}
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement