SFML将精灵放在中心

SFML Place Sprite on center

本文关键字:在中心 精灵 SFML      更新时间:2023-10-16

我一直在尝试解决这个问题大约一个小时或更长时间......但找不到任何有用的答案。我试图在窗口中央放置一个精灵,但它出现在TOP_LEFT上。这是我类的构造函数,如您所见,我将 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;
}
在类的主体中声明变量

意味着类全局可以看到它们,如果在构造函数中重新声明变量,它将接管全局变量的角色。这称为变量阴影。对变量的所有修改都将起作用,但是一旦离开构造函数/函数/方法的范围,那么您将丢失信息,因为您的属性变量未被修改。

有关范围的更多信息:http://en.cppreference.com/w/cpp/language/scope

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