我一直在尝试用C ++ SFML进行精灵显示,但是使用了类。但是,当我编译并运行程序时,没有任何内容出现:也没有错误。如果有人愿意帮助我,我很确定这是一个愚蠢的错误。不确定问题出在哪里,所以我也包含了头文件:
(main中唯一发生的事情就是创建了'Game'对象)
Game.h
#ifndef GAME_H
#define GAME_H
#include <SFML/Graphics.hpp>
#include "Player.h"
class Game
{
public:
Game();
private:
//Variables
sf::RenderWindow _mainWindow;
enum _gameState { Playing, Paused, Splash, Menu };
//Methods
void gameLoop();
};
#endif // GAME_H
Game.cpp
#include "Game.h"
#include "Player.h"
Game::Game() {
//Variables
_mainWindow.create(sf::VideoMode(960, 640), "Game", sf::Style::Titlebar | sf::Style::Close);
_mainWindow.setFramerateLimit(60);
//Start Game Loop
gameLoop();
}
void Game::gameLoop() {
Player player;
while(_mainWindow.isOpen()) {
sf::Event ev;
while(_mainWindow.pollEvent(ev)) {
if(ev.type == sf::Event::Closed)
_mainWindow.close();
if(ev.type == sf::Event::KeyPressed) {
if(ev.key.code == sf::Keyboard::Escape)
_mainWindow.close();
}
}
//Draw Stuff
_mainWindow.clear(sf::Color::White);
player.drawSprite(_mainWindow);
_mainWindow.display();
}
}
Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <SFML/Graphics.hpp>
#include <iostream>
class Player
{
public:
Player();
void drawSprite(sf::RenderWindow& window);
private:
bool loadSprite();
sf::Texture _playerTexture;
sf::Sprite _playerSprite;
};
#endif // PLAYER_H
Player.cpp
#include "Player.h"
#include "Game.h"
Player::Player()
{
if(!Player::loadSprite()){
return;
}
}
bool Player::loadSprite() {
sf::Texture _playerTexture;
if(!_playerTexture.loadFromFile("img/darkguy.png", sf::IntRect(32,32,32,32))) {
std::cout << "Failed to load player image" << std::endl;
return false;
} else {
sf::Sprite _playerSprite;
_playerSprite.setTexture(_playerTexture);
}
return true;
}
void Player::drawSprite(sf::RenderWindow& window) {
//sprite.setTextureRect(sf::IntRect(10, 10, 32, 32));
window.draw(_playerSprite);
std::cout << "Sprite Drawn Successfully" << std::endl;
}
对于文本墙感到抱歉,我是编程的初学者,这是我在stackoverflow上的第一篇文章。此外,如果有人发现任何更有效的方式来做某事,请随时指出:)
在此先感谢:P
答案 0 :(得分:3)
你在这里声明一个新的本地_playerSprite:
} else {
sf::Sprite _playerSprite;
_playerSprite.setTexture(_playerTexture);
}
而是使用现有的类成员:
} else {
_playerSprite.setTexture(_playerTexture);
}
您可能也希望从此代码中删除第一行,同样的问题:
bool Player::loadSprite()
{
sf::Texture _playerTexture; // <--- local redeclaration
答案 1 :(得分:1)
从我的记忆中看:纹理必须是你班上的一员;它在您使用它时必须存在。在您的代码中,_playerTexture在loadSprite()的末尾被销毁。 _playerSprite也有同样的问题。
修改强>
您不必在方法中重新声明班级成员:
bool Player::loadSprite() {
sf::Texture _playerTexture;
if(!_playerTexture.loadFromFile("img/darkguy.png", sf::IntRect(32,32,32,32))) {
std::cout << "Failed to load player image" << std::endl;
return false;
} else {
sf::Sprite _playerSprite;
_playerSprite.setTexture(_playerTexture);
}
return true;
}
应该是:
bool Player::loadSprite() {
if(!_playerTexture.loadFromFile("img/darkguy.png", sf::IntRect(32,32,32,32))) {
std::cout << "Failed to load player image" << std::endl;
return false;
} else {
_playerSprite.setTexture(_playerTexture);
}
return true;
}
(PS:您的代码不尊重SRP(单一责任原则),玩家不必自行展示。)