SFML 将 Sprite 置于中心

SFML Place Sprite on center

我已经尝试解决这个问题大约一个小时或更长时间...但找不到任何有用的答案。 我试图在 window 的中心放置一个精灵,但它显示在 TOP_LEFT 上。这是我的 class 的构造函数,如您所见,我将 surface.width 和 surface.height 除以 2

Spaceship::Spaceship(sf::RenderWindow& game_window){
    auto surface = game_window.getSize();
    signed int ss_x = surface.x/2;
    signed int ss_y = surface.y/2;
    
    int ss_width = 128;
    int ss_height = 128;
    int ss_radius = ss_width/2;
}
  ///////////////////////////////////////////
 // For displaying the sprite on window   //
///////////////////////////////////////////
void Spaceship::drawsprite(sf::RenderWindow& game_window){
    sf::Texture ship;
    if (!ship.loadFromFile(resourcePath() + "space-shuttle-64.png")) {
        return EXIT_FAILURE;
    }
    sf::Sprite ss_sprite(ship);
    ss_sprite.setPosition(ss_x, ss_y);
    game_window.draw(ss_sprite);
}

我也尝试过:

   auto surface = game_window.RenderWindow::getSize();
    signed int ss_x = surface.x/2;
    signed int ss_y = surface.y/2;

但这也无济于事。

更新:

我试图打印在构造函数中定义的变量,但我得到的都是 0。所以我的问题似乎是访问问题。但是没有错误或警告告诉我这一点。

更新 2:

这是头文件:

#ifndef Spaceship_hpp
#define Spaceship_hpp
#include <iostream>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <stdio.h>

using namespace std;

class Spaceship {
public:
    Spaceship();
    Spaceship(sf::RenderWindow&);
    ~Spaceship();
     void moveship(char);
     void drawsprite(sf::RenderWindow&);
    
private:
    signed int ss_x, ss_y;
    unsigned int ss_speed;
    int ss_width, ss_height, ss_radius;
    
};

#endif /* Spaceship_hpp */

您没有在构造函数中正确初始化属性。

Spaceship::Spaceship(sf::RenderWindow& game_window){
    auto surface = sf::VideoMode::getDesktopMode();
    signed int ss_x = surface.width/2;
    signed int ss_y = surface.height/2;

    int ss_width = 128;
    int ss_height = 128;
    int ss_radius = ss_width/2;
}

应该是

Spaceship::Spaceship(sf::RenderWindow& game_window){
    auto surface = sf::VideoMode::getDesktopMode();
    ss_x = surface.width/2;
    ss_y = surface.height/2;

    ss_width = 128;
    ss_height = 128;
    ss_radius = ss_width/2;
}

在class的主体中声明变量意味着它们在class的全局范围内可见,如果您在构造函数中重新声明一个变量,它将接替全局变量的角色。这称为 变量阴影 。对该变量的所有修改都将起作用,但是一旦您离开 constructor/function/method 的范围,您就会丢失信息,因为您的属性变量未被修改。

有关作用域的更多信息:http://en.cppreference.com/w/cpp/language/scope

有关变量阴影的更多信息:https://en.wikipedia.org/wiki/Variable_shadowing?oldformat=true