gpt4 book ai didi

C++ SFML Sprite 未绘制,但未发生错误

转载 作者:行者123 更新时间:2023-11-30 01:49:48 25 4
gpt4 key购买 nike

我一直在尝试使用类在 C++ SFML 中制作 Sprite 显示。但是,当我编译并运行该程序时,什么也没有出现:也没有错误。

(main 中唯一发生的事情是创建了一个“游戏”对象)

游戏.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

游戏.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;

}

最佳答案

您在这里声明了一个新的本地 _playerSprite:

} else {
sf::Sprite _playerSprite;
_playerSprite.setTexture(_playerTexture);
}

相反,使用现有的类成员:

} else {
_playerSprite.setTexture(_playerTexture);
}

您可能还想删除此代码的第一行,同样的问题:

bool Player::loadSprite() 
{
sf::Texture _playerTexture; // <--- local redeclaration

关于C++ SFML Sprite 未绘制,但未发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28395066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com