我正在使用带有c ++的SFML来尝试游戏开发,我想将我的播放器功能放在一个新类中,但我似乎无法在我的main.cpp文件中使用我的播放器精灵对象。
这是我的标题,Header.cpp和Main.cpp文件:
部首:
#ifndef PLY_H
#define PLY_H
#include <SFML/Graphics.hpp>
class Ply
{
public:
Ply(); //Constructor
Player; //sf::Sprite Object
};
#endif
Header.cpp文件:
#include "Ply.h"
#include <SFML/Graphics.hpp>
using namespace std;
Ply::Ply()
{
sf::Texture Playertex;
if(!Playertex.loadFromFile("Gabe.jpg"))
{
//Error code here
}
sf::Sprite Player;
Player.setTexture(Playertex);
}
和main.cpp:
#include <SFML/Graphics.hpp>
#include "Ply.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(800,800),"Game");
Ply ply;
while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
window.close();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
ply.Player.move(sf::Vector2f(0,-5));
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
ply.Player.move(sf::Vector2f(0,5));
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
ply.Player.move(sf::Vector2f(-5,0));
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
ply.Player.move(sf::Vector2f(5,0));
}
if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
sf::Vector2i MsLoc = sf::Mouse::getPosition(window);
ply.Player.setPosition(MsLoc.x,MsLoc.y);
}
}
window.clear();
window.draw(ply.Player);
window.display();
}
return 0;
}
在控制台中,它说“ply不是类或命名空间”
帮助?
答案 0 :(得分:1)
我认为问题在于您创建了一个新的本地sf::Sprite
对象并将纹理加载到该对象中而不是同名的类成员sf:Sprite
:
Ply::Ply()
{
if(!Playertex.loadFromFile("Gabe.jpg"))
{
//Error code here
}
sf::Sprite Player; // This is NOT the sf::Sprite in your class!!
Player.setTexture(Playertex);
}
只需删除它即可解决您的问题:
Ply::Ply()
{
sf::Texture Playertex;
if(!Playertex.loadFromFile("Gabe.jpg"))
{
//Error code here
}
Player.setTexture(Playertex);
}
至少会给你的会员sf::Sprite
一个类型:
class Ply
{
public:
Ply();
sf::Sprite Player; // Needed a type!
sf::Texture Playertex; // this also needs to be a member
};
答案 1 :(得分:1)
Galik发现了代码中的一个错误。另一个与the white square problem有关。基本上,退出Ply
的构造函数时会破坏纹理。您需要将纹理作为类的字段而不是局部变量。