Ajuda com SFML em C++

7 respostas
J

Pessoal, tenho uma duvida, tenho um código em C++ com SFML, desenhei uma figuras na tela e fiz interação com o teclado para movimento das mesmas, mas gostaria de saber como eu faço para fazer cada figura de uma vez aumentar e diminuir de tamanho?
Se alguem puder me ajudar eu agradeço, segue o código:

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

int main() {
    // Inicializacao da biblioteca
    sf::RenderWindow* app = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "Teste de imput do teclado!");
    int xCircle = 300;
    int yCircle = 300;
    int xLine = 10;
    int yLine = 10;
    int x1Line = 100;
    int y1Line = 100;
    int xRect = 150;
    int yRect = 150;
    int x1Rect = 200;
    int y1Rect = 200;
    int xPolygon = 100;
    int yPolygon = 100;
    int x1Polygon = 150;
    int y1Polygon = 200;
    int x2Polygon = 80;
    int y2Polygon = 150;

    // Gamelooping
    while (app->IsOpened()) {
        // Process game input
        sf::Event* event = new sf::Event();
        while (app->GetEvent(*event)) {
            if (event->Type == sf::Event::Closed) {
                app->Close();
            }
        }
        if (app->GetInput().IsKeyDown(sf::Key::Escape)) {
            return EXIT_SUCCESS;
        }

        // Simulate Game World movimentation
        if (app->GetInput().IsKeyDown(sf::Key::Up)) yCircle--;
        else if (app->GetInput().IsKeyDown(sf::Key::Down)) yCircle++;
        else if (app->GetInput().IsKeyDown(sf::Key::Left)) xCircle--;
        else if (app->GetInput().IsKeyDown(sf::Key::Right)) xCircle++;

        if (app->GetInput().IsKeyDown(sf::Key::W)) yLine--;
        else if (app->GetInput().IsKeyDown(sf::Key::S)) yLine++;
        else if (app->GetInput().IsKeyDown(sf::Key::A)) xLine--;
        else if (app->GetInput().IsKeyDown(sf::Key::D)) xLine++;

        if (app->GetInput().IsKeyDown(sf::Key::W)) y1Line--;
        else if (app->GetInput().IsKeyDown(sf::Key::S)) y1Line++;
        else if (app->GetInput().IsKeyDown(sf::Key::A)) x1Line--;
        else if (app->GetInput().IsKeyDown(sf::Key::D)) x1Line++;

        if (app->GetInput().IsKeyDown(sf::Key::I)) yRect--;
        else if (app->GetInput().IsKeyDown(sf::Key::K)) yRect++;
        else if (app->GetInput().IsKeyDown(sf::Key::J)) xRect--;
        else if (app->GetInput().IsKeyDown(sf::Key::L)) xRect++;

        if (app->GetInput().IsKeyDown(sf::Key::I)) y1Rect--;
        else if (app->GetInput().IsKeyDown(sf::Key::K)) y1Rect++;
        else if (app->GetInput().IsKeyDown(sf::Key::J)) x1Rect--;
        else if (app->GetInput().IsKeyDown(sf::Key::L)) x1Rect++;

        if (app->GetInput().IsKeyDown(sf::Key::T)) yPolygon--;
        else if (app->GetInput().IsKeyDown(sf::Key::G)) yPolygon++;
        else if (app->GetInput().IsKeyDown(sf::Key::F)) xPolygon--;
        else if (app->GetInput().IsKeyDown(sf::Key::H)) xPolygon++;

        if (app->GetInput().IsKeyDown(sf::Key::T)) y1Polygon--;
        else if (app->GetInput().IsKeyDown(sf::Key::G)) y1Polygon++;
        else if (app->GetInput().IsKeyDown(sf::Key::F)) x1Polygon--;
        else if (app->GetInput().IsKeyDown(sf::Key::H)) x1Polygon++;

        if (app->GetInput().IsKeyDown(sf::Key::T)) y2Polygon--;
        else if (app->GetInput().IsKeyDown(sf::Key::G)) y2Polygon++;
        else if (app->GetInput().IsKeyDown(sf::Key::F)) x2Polygon--;
        else if (app->GetInput().IsKeyDown(sf::Key::H)) x2Polygon++;

        // Render
        app->Clear(sf::Color(255, 255, 255));

        sf::Shape Line = sf::Shape::Line(xLine, yLine, x1Line, y1Line, 3, sf::Color(0,0,0), 1, sf::Color(255, 255, 0));
        sf::Shape Circle = sf::Shape::Circle(xCircle, yCircle, 50, sf::Color(125, 200, 240), 1, sf::Color(0, 0, 0));
        sf::Shape Rect = sf::Shape::Rectangle(xRect, yRect, x1Rect, y1Rect, sf::Color(35, 200, 100), 1, sf::Color(0, 0, 0));

        sf::Shape Polygon;
        Polygon.AddPoint(xPolygon, yPolygon, sf::Color(255, 0, 0),     sf::Color(0, 128, 128));
        Polygon.AddPoint(x1Polygon, y1Polygon, sf::Color(255, 85, 85),   sf::Color(0, 128, 128));
        Polygon.AddPoint(x2Polygon, y2Polygon, sf::Color(255, 170, 170), sf::Color(0, 128, 128));

        app->Draw(Line);
        app->Draw(Circle);
        app->Draw(Rect);
        app->Draw(Polygon);
        app->Display();
    };
    return EXIT_SUCCESS;
}

Desde ja eu agradeço

7 Respostas

J

Olá,

Esse seu código está muito monolítico. Tenta quebrar tudo isso em métodos menores(responsáveis por criar o background, sprites, etc..)

sf::Shape Line = sf::Shape::Line(xLine, yLine, x1Line, y1Line, 3, sf::Color(0,0,0), 1, sf::Color(255, 255, 0));  
        sf::Shape Circle = sf::Shape::Circle(xCircle, yCircle, 50, sf::Color(125, 200, 240), 1, sf::Color(0, 0, 0));  
        sf::Shape Rect = sf::Shape::Rectangle(xRect, yRect, x1Rect, y1Rect, sf::Color(35, 200, 100), 1, sf::Color(0, 0, 0));  
  
        sf::Shape Polygon;  
        Polygon.AddPoint(xPolygon, yPolygon, sf::Color(255, 0, 0),     sf::Color(0, 128, 128));  
        Polygon.AddPoint(x1Polygon, y1Polygon, sf::Color(255, 85, 85),   sf::Color(0, 128, 128));  
        Polygon.AddPoint(x2Polygon, y2Polygon, sf::Color(255, 170, 170), sf::Color(0, 128, 128));  
  
        app->Draw(Line);  
        app->Draw(Circle);  
        app->Draw(Rect);  
        app->Draw(Polygon);  
        app->Display();

Você pode criar um vetor de sf::Shape para guardar o estado de todas essas formas:

sf::Shape *formas = new sf::Shape[num_shapes];

depois disso criar um método para gerenciar a animação desses objetos que estão guardados nesse vetor.

Eu não conheço essa biblioteca. É uma egine para jogos?

E

Eufemismo para “linguição” - em C ou C++ normalmente não é necessário escrever código linguição (ou seja, mais de 60 linhas em um único método) para ter bom desempenho, já que o compilador e o linker tomam conta disso se houver algum overhead para chamada a métodos.

Às vezes é necessário efetuar algum “loop unrolling” manualmente, mas isso é melhor resolvido com alguma macro ou então com alguma extensão da linguagem como o OpenMP.

J

SFML é um biblioteca.

Ta, mas mesmo o código estando muito extenso, como eu faço um comando para aumentar e diminuir o tamanho de cada figura através de entradas do teclado?

J
jct:
SFML é um biblioteca.

Ta, mas mesmo o código estando muito extenso, como eu faço um comando para aumentar e diminuir o tamanho de cada figura através de entradas do teclado?

Você não construiu o círculo com os seguintes atributos?

sf::Shape Circle = sf::Shape::Circle(xCircle, yCircle, 50, sf::Color(125, 200, 240), 1, sf::Color(0, 0, 0));

Na lógica do seu jogo, você precisa de um método para limpar a superfície onde os objetos são pintados. Então você cria o mesmo objeto com menor proporção.

sf::app->clear(); //isso é uma suposição. Não deve existir na biblioteca com esse nome.

 sf::Shape Circle = sf::Shape::Circle(xCircle, yCircle, 20, sf::Color(125, 200, 240), 1, sf::Color(0, 0, 0));

O seu problema pode ser o fato da superfície não estar sendo atualizada, ou o seu código de input pelo teclado lá em cima estar falhando...
Precisa olhar na documentação da biblioteca como se faz isso. Mas a princípio reestruturar esse código é primeira coisa que precisaria fazer, para poder ficar mais fácil pra você mesmo entender a lógica da coisa.

********** editado **************

Desculpe, eu não havia visto

// Render  
        app->Clear(sf::Color(255, 255, 255));

A primeira vista não parece ter problema nenhum. Reveja a lógica nesses bloco com um breakpoint, para ver se está entrando nas condições corretamente:

// Simulate Game World movimentation  
        if (app->GetInput().IsKeyDown(sf::Key::Up)) yCircle--;  
        else if (app->GetInput().IsKeyDown(sf::Key::Down)) yCircle++;  
        else if (app->GetInput().IsKeyDown(sf::Key::Left)) xCircle--;  
        else if (app->GetInput().IsKeyDown(sf::Key::Right)) xCircle++;  
  
        if (app->GetInput().IsKeyDown(sf::Key::W)) yLine--;  
        else if (app->GetInput().IsKeyDown(sf::Key::S)) yLine++;  
        else if (app->GetInput().IsKeyDown(sf::Key::A)) xLine--;  
        else if (app->GetInput().IsKeyDown(sf::Key::D)) xLine++;  
  
        if (app->GetInput().IsKeyDown(sf::Key::W)) y1Line--;  
        else if (app->GetInput().IsKeyDown(sf::Key::S)) y1Line++;  
        else if (app->GetInput().IsKeyDown(sf::Key::A)) x1Line--;  
        else if (app->GetInput().IsKeyDown(sf::Key::D)) x1Line++;  
  
        if (app->GetInput().IsKeyDown(sf::Key::I)) yRect--;  
        else if (app->GetInput().IsKeyDown(sf::Key::K)) yRect++;  
        else if (app->GetInput().IsKeyDown(sf::Key::J)) xRect--;  
        else if (app->GetInput().IsKeyDown(sf::Key::L)) xRect++;  
  
        if (app->GetInput().IsKeyDown(sf::Key::I)) y1Rect--;  
        else if (app->GetInput().IsKeyDown(sf::Key::K)) y1Rect++;  
        else if (app->GetInput().IsKeyDown(sf::Key::J)) x1Rect--;  
        else if (app->GetInput().IsKeyDown(sf::Key::L)) x1Rect++;  
  
        if (app->GetInput().IsKeyDown(sf::Key::T)) yPolygon--;  
        else if (app->GetInput().IsKeyDown(sf::Key::G)) yPolygon++;  
        else if (app->GetInput().IsKeyDown(sf::Key::F)) xPolygon--;  
        else if (app->GetInput().IsKeyDown(sf::Key::H)) xPolygon++;  
  
        if (app->GetInput().IsKeyDown(sf::Key::T)) y1Polygon--;  
        else if (app->GetInput().IsKeyDown(sf::Key::G)) y1Polygon++;  
        else if (app->GetInput().IsKeyDown(sf::Key::F)) x1Polygon--;  
        else if (app->GetInput().IsKeyDown(sf::Key::H)) x1Polygon++;  
  
        if (app->GetInput().IsKeyDown(sf::Key::T)) y2Polygon--;  
        else if (app->GetInput().IsKeyDown(sf::Key::G)) y2Polygon++;  
        else if (app->GetInput().IsKeyDown(sf::Key::F)) x2Polygon--;  
        else if (app->GetInput().IsKeyDown(sf::Key::H)) x2Polygon++;
J

Eufemismo para “linguição” - em C ou C++ normalmente não é necessário escrever código linguição (ou seja, mais de 60 linhas em um único método) para ter bom desempenho, já que o compilador e o linker tomam conta disso se houver algum overhead para chamada a métodos.

Às vezes é necessário efetuar algum “loop unrolling” manualmente, mas isso é melhor resolvido com alguma macro ou então com alguma extensão da linguagem como o OpenMP.

espaguetão também… ^ ^

J

Eu revi o codigo e ta rodando lisinho, tipo eu queria uma linha de comando para aumentar a figura quando eu apertasse ‘+’ no teclado, simplesinho.

J
jct:
Eu revi o codigo e ta rodando lisinho, tipo eu queria uma linha de comando para aumentar a figura quando eu apertasse '+' no teclado, simplesinho.
mapeia a tecla "plus":
if (app->GetInput().IsKeyDown(sf::Key::Plus)){// não sei se Plus existe, é  uma suposição, então olhe a documentação
     rCircle++; //raio
  
} 

//clear
app->Clear(255,255,255);

//desenha novamente

sf::Shape Circle = sf::Shape::Circle(xCircle, yCircle, rCircle, sf::Color(125, 200, 240), 1, sf::Color(0, 0, 0));
Criado 4 de setembro de 2012
Ultima resposta 5 de set. de 2012
Respostas 7
Participantes 3