在SFML

时间:2015-11-16 20:45:36

标签: c++ sfml

所以我是新手一般的堆栈溢出和编程,所以请原谅我,如果我做了或者说出了无知的明显愚蠢。

所以,我最近一直在努力学习如何使用SFML,到目前为止,它一直很好,但最近,我一直在尝试编写移动相机。让我告诉你我的代码:

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

#include <iostream>
#include <cstdlib>

using namespace std;
using namespace sf;

bool frame60 = true;

void print(string inputText) {
    bool consoleOn = true;
    if(consoleOn == true) { cout << inputText; }
}

void start() {
    sf::View view1;
    view1.reset(sf::FloatRect(300, 200, 300, 200));
    view1.setCenter(0, 0);

    RenderWindow window(VideoMode(1600, 900), "Test Game");
    window.setView(view1);
    window.setKeyRepeatEnabled(false);
    switch(frame60) {
    case true:
        window.setFramerateLimit(60);
        break;
    case false:
        window.setFramerateLimit(30);
        break;
    default:
        window.setFramerateLimit(60);
        break;
    }

    Texture testure;
    testure.loadFromFile("vsm.png");
    Sprite testsprite;
    testsprite.setTexture(testure);

    testsprite.setOrigin(0, 0);

    float playerx = 0;
    float playery = 0;


    while(window.isOpen()) {
        Event event;
        while(window.pollEvent(event)) {
            switch(event.type) {
                //Making the window closable
            case Event::Closed:
                window.clear();
                window.close();
                break;
            }
        }

        if(Keyboard::isKeyPressed(Keyboard::A)) {
            playerx += 0.5;
        }
        if(Keyboard::isKeyPressed(Keyboard::D)) {
            playerx -= 0.5;
        }

        testsprite.setOrigin(playerx, playery);

        view1.setCenter(playerx, playery);
        window.draw(testsprite);
        window.display();
        window.clear();

        cout << playerx << endl;
    }
}

int main() {
    start();
    return 0;
}

(不要介意我使用自制的启动功能,这只是我试图更好地了解如何使用c ++一般。就像这个程序的许多不必要的部分可能的情况一样,因为这程序只是一个学习练习。)

所以,基本上,正如你所看到的,我有一个移动的蓝色矩形。但是,我希望相机跟随它,所以在游戏循环中,我告诉我的视图将其中心设置为矩形所在的位置。很基本的。问题是,屏幕不动。我按下我设置的左右键,我仍然看到盒子在黑色背景上移动,如果视图跟随它,它根本不会移动,并且唯一的证据表明它正在移动应该是在我的控制台窗口中。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您想对窗口视图进行任何更改,则必须在之后调用sf::RenderWindow::setView。您只是修改view1,而不是sf::RenderWindow存储和使用的副本。

Reference

我会在另外的范围内更新此视图,而不是污染外部范围:

{
    sf::View view = window.getView(); // get the current view, view1 is not needed here
    // modify the view
    window.setView(view);
}