SFML将精灵放在中心
SFML Place Sprite on center
我一直在尝试解决这个问题大约一个小时或更长时间......但找不到任何有用的答案。我试图在窗口中央放置一个精灵,但它出现在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
相关文章:
- 从精灵表在 sfml 中为精灵制作动画
- 如何在精灵表上的两个不同部分之间来回切换,同时用户仍使用 SFML 持有密钥
- 我的精灵使用名为 ASGE 的C++框架卡在屏幕边缘
- 有没有办法在链接时设置精灵需要字段?
- 在不同位置渲染相同精灵的数组
- 为什么精灵在 cocos2d-x 中颤抖
- SFML:在旋转SFML的精灵时,如何解决精灵质量下降
- 在鼠标位置移动精灵
- 在 OpenCV 和 C++ 中查找距轮廓中心最近的黑色像素
- 在矩形形状的中心对齐文本
- 在 Cocos2d-x 中一次使用多个精灵表
- 精灵不在SFML中移动
- 如何使用OpenGL在中心的按钮上绘制正方形
- 如何在中心旋转二维对象
- 在中心绘制图像,同时保持纵横比
- 黑色背景,图像在中心使用 GDI
- Cocos2d-x 3.2 EventListener在子精灵中不工作
- 在工作精灵系统中添加实例的问题
- OpenCV filter2D:是否有任何使用内核不锚定在中心
- 在中心位置渲染模型不显示(已修改)