-
Hello, I'm trying to load a texture and a sprite. This works fine as long as I define them inside my .cpp file, but if I move the texture to the header file nothing is shown in the window.
Here is the header file:
#pragma once
#include <SFML/Graphics.hpp>
using namespace sf;
class GameObject
{
public:
GameObject();
~GameObject();
void Draw(RenderWindow *);
void Update();
Sprite sprite;
Texture texture;
};
This is the .cpp file:
GameObject::GameObject()
{
if (!texture.loadFromFile("sprite.png"))
{
}
sprite.setTexture(texture);
}
void GameObject::Draw(RenderWindow * window)
{
window->draw(GameObject::sprite);
}
I tried debugging it at it looks like my texture doesn't have a y size when its defined inside the header. Why is that?
Note: I'm a C# programmer who is trying to play around with C++, there might be some things, that I dont understand yet.
-
are you sure the texture is loaded at all? i like this kind of "debugging" sometimes
if (!texture.loadFromFile("sprite.png")){
std::cout << "texture not loaded!";}
else {
std::cout << "texture loaded!";
}
you could also try using the complete namespace sf::Texture texture;
and of course, make sure the image name and folder are correct.
other than that, the code doesn't seems to have any errors to me...
-
I'm sure that its loading the texture, it works fine if I cut the texture line from the header file into the .cpp file. I have no idea why it isn't working.
-
This works
#include <SFML/Graphics.hpp>
class GameObject
{
public:
GameObject();
~GameObject();
void Draw(sf::RenderWindow &);
void Update();
const std::string textureFile = "texture.png";
sf::Texture texture;
sf::Sprite sprite;
};
GameObject::GameObject()
{
if (!texture.loadFromFile(textureFile))
{
}
sprite.setTexture(texture);
}
GameObject::~GameObject()
{
}
void GameObject::Draw(sf::RenderWindow& window)
{
window.draw(GameObject::sprite);
}
int main()
{
GameObject object;
sf::RenderWindow window;
window.create(sf::VideoMode(800, 600), "test");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
object.Draw(window);
window.display();
}
return 0;
}
-
Please read this (http://en.sfml-dev.org/forums/index.php?topic=5559.msg36368#msg36368) carefully and adjust your problem description accordingly.
The crystal ball says you perform an unintended copy.
-
This works
You should try passing the render window as a reference instead of a pointer to `GameObject::Draw` like you're doing here.
-
You should try passing the render window as a reference instead of a pointer to `GameObject::Draw` like you're doing here.
That won't make any difference, but it can be a good code style to express "null pointers are not allowed".