Sam Talbot Sam Talbot - 2 months ago 17
C++ Question

SFML Objects In Header File

I'm using SFML with c++ to try game development and I want to put my player functions in a new class, But i cant seem to use my player sprite object in my main.cpp file.

This Is My Header, Header.cpp and Main.cpp file:

Header:

#ifndef PLY_H
#define PLY_H
#include <SFML/Graphics.hpp>

class Ply
{
public:
Ply(); //Constructor
Player; //sf::Sprite Object


};

#endif


Header.cpp file:

#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);

}


And 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;
}


In the console it says "ply is not a class or namespace"

Help?

Answer

I think the problem is that you creat a new, local sf::Sprite object and load the texture into that instead of the class member sf:Sprite of the same name:

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);

}

Just remove it and that should fix your problem:

Ply::Ply()
{
    sf::Texture Playertex;
    if(!Playertex.loadFromFile("Gabe.jpg"))
    {
        //Error code here
    }

    Player.setTexture(Playertex);

}

At least it will when you give your member sf::Sprite a type:

class Ply
{
public:
    Ply();

    sf::Sprite Player; // Needed a type!
    sf::Texture Playertex; // this also needs to be a member

};