SFML Class Sprite Loading Function Help

Started by
7 comments, last by Cryusaki 10 years, 8 months ago

So I created a basic pong game in SFML using a single main.cpp file. Now I want to better organize the game so I created a seperate class to handle loading in the sprites, displaying them and then destroying them. I wanted to keep everything simple so I made sure the loading in file was under Public:

This is a line of code I use to load in a sprite


    sf::Texture paddle;
    if(!paddle.loadFromFile("Paddle.png"))
        std::cout << "Could not load paddle." << std::endl;
    sf::Sprite sPaddle;
    sPaddle.setTexture(paddle); 

So in the main program I make a call to that function however when I debug and run the program it says that sPaddle was not declared in this scope. The function was called directly after declaring my variables and initializing the screen. Also the function is in the public section of the class. The line of code that is trying to call sPaddle specifically


sPaddle.setPosition(0, SCREENHEIGHT/2 - (PADDLEHEIGHT/2));

comes directly after. What is wrong?

I never uploaded code before so if you need to look at it just let me know, Thanks smile.png

Advertisement

I created a seperate class to handle loading in the sprites, displaying them and then destroying them.

That doesn't sound very efficient! You want to load them, display them many times, and when they are no longer needed, then you destroy them. But if you load, draw, destroy every time you want to draw them, your code will slow to a crawl. Or maybe I'm misunderstanding what you mean! smile.png

This is a line of code I use to load in a sprite


    if(!paddle.loadFromFile("Paddle.png"))
        std::cout << "Could not load paddle." << std::endl;
    sf::Sprite sPaddle;
    sPaddle.setTexture(paddle);

Don't forget that in SFML, the lifetime of the texture must last longer than the lifetime of the sprite that the texture is set to. The sprite doesn't take ownership of the texture (since the same texture can be set to multiple sprites), so you have to handle the lifetime of the texture yourself.

This isn't related to your error message, but I think it's another bug you might have in your program once you resolve your error message. I can't tell for sure until I see the code though.

So if you do this:


{
    sf::Sprite mySprite;
    
    {
        sf::Texture myTexture;
        //...
        
        mySprite.setTexture(myTexture);
        
    } //<--- 'myTexture' gets destroyed here when it goes out of scope, so mySprite now has an invalid texture!
    
}

So in the main program I make a call to that function however when I debug and run the program it says that sPaddle was not declared in this scope.

I think you're using the words 'debug' and 'run' wrong.

First, your code compiles. This is where you are likely getting your error message.
Second, you run your program after it is compiled.
Third, if you are running your program in debug mode and using a debugger, then you are debugging your program.

This is just programmer in-speak we use to communicate to other programmers faster, so the meaning of the words matter for clear communication.

I never uploaded code before so if you need to look at it just let me know, Thanks smile.png

Yep, to help further, we will need to see it. This forum's post editor has a button near the type that says 'code'.

htk0.jpg

Click that, then copy+paste the code into the box that appears. We need the files (both header and source) of the new helper class you wrote, as well as the function that is giving you the compiler error.

Also, posting the compiler error itself would help - compiler errors, though confusing at first, actually do try to tell you what is wrong, you just need to learn how to read them (which comes overtime).

The seperate class to load, display and destroy the sprites is my form a Sprite Manager class, instead of having a wall of text in the main main.cpp file that loads all the files in I want to move it to another class and call that method (sorry I think I used the word function incorrectly in my last post) just as a way to sort the code up visually and mentally. The class will have a seperate methods to handle displaying at the end of the loop and then kill the images once the loop has ended completely. Not during the loop

Also my bad about the snippit of code that is showing the sprite to texture bit. I left out a line, embarassing :S

It should be edited back in now but incase it isnt here is the revised version


    sf::Texture paddle; // Here is the missing line
    if(!paddle.loadFromFile("Paddle.png"))
        std::cout << "Could not load paddle." << std::endl;
    sf::Sprite sPaddle;
    sPaddle.setTexture(paddle);

I have not taken an official programming language courses so my terminoligy is unsurprisingly poor, all my knowledge comes from free online help all over the web. Good to know though!


    sPaddle.setPosition(0, SCREENHEIGHT/2 - (PADDLEHEIGHT/2));  // Line 31

And ther Error message that is coming up in the build log is saying


|31|error: 'sPaddle' was not declared in this scope|

That's still not enough code to solve your problem. I need to see the Sprite Manager class, and the part of the code (the entire function) where you create the Sprite Manager class, and the part of the code (the entire function) where you are using the Sprite Manager class to retrieve the the sprite and set it. I don't mind if it's too messy - I can read through the mess - but if you cut out pieces of your actual code before posting then it makes it harder for us to find the problem, and instead we have to guess what the problem is.

For example, I need to see the entire function that contains this line: (in addition to the entire Sprite Manager class).


sPaddle.setPosition(0, SCREENHEIGHT/2 - (PADDLEHEIGHT/2));

This forum's post editor has a button near the type that says 'code', and you can copy+paste your code into the box that it pops up. Just paste everything into it, even multiple files worth of text, and I'll sort it out and find the problem.

htk0.jpg

I have not taken and official programming language courses so my terminoligy is unsurprisingly poor, all my knowledge comes from free online help all over the web. Good to know though!

Same here! I'm entirely internet and book taught. I'm not trying to nitpick your terminology, just pointing out that if you are getting a 'not declared in that scope' message, than you can't truly be running/executing or debugging the code, because that's a compiler error not a runtime error - which is an important clue in solving the problem.

Terminology is something learned over time, piece by piece. Whether you say method or function doesn't bother me, because it's not related to the problem you are having. I get terminology wrong all the time. happy.png

Main.cpp


#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include "SpriteManager.h"

int main()
{
    SpriteManager SpriteMan;

    const int PADDLEWIDTH = 30, PADDLEHEIGHT = 90;
    const int BALLWIDTH = 30, BALLHEIGHT = 30;
    const int SCREENWIDTH = 800, SCREENHEIGHT = 600;

    float ballvelx = -0.75, ballvely = 0;
    float bpdelta = 0;
    int p1Score = 0, p2Score = 0;

    bool bLeft = true;

    float frameCounter = 0, switchFrame = 100, frameSpeed = 500;

    sf::RenderWindow window(sf::VideoMode(800, 600), "Pong Clone");

    SpriteMan.loadSprites();

    window.setKeyRepeatEnabled(false);

    sf::Clock clock;
    sf::Time time;

    sPaddle.setPosition(0, SCREENHEIGHT/2 - (PADDLEHEIGHT/2));
    sComputer.setPosition(SCREENWIDTH-PADDLEWIDTH , SCREENHEIGHT/2 - (PADDLEHEIGHT/2));
    sBall.setPosition(SCREENWIDTH/2 - (BALLWIDTH/2) , SCREENHEIGHT/2 - (BALLHEIGHT/2));

    while (window.isOpen())
    {
        sf::Event Event;
        while (window.pollEvent(Event))
        {
            if (Event.type == sf::Event::Closed)
                window.close();
        }

    switch(Event.type)
    {
        case sf::Event::KeyPressed:
            if(Event.key.code == sf::Keyboard::Up)
                sPaddle.move(0, -1);
            else if(Event.key.code == sf::Keyboard::Down)
                sPaddle.move(0, 1);
    }

            // Collision Check
        // Paddle/Screen Collision
        if(sPaddle.getPosition().y <= 0)
            sPaddle.setPosition(0,0);
        else if(sPaddle.getPosition().y + PADDLEHEIGHT >= SCREENHEIGHT)
            sPaddle.setPosition(0,SCREENHEIGHT - PADDLEHEIGHT);
        // Ball/Screen Collision
        if(sBall.getPosition().y <= 0)
            ballvely = ballvely * -1;
        else if(sBall.getPosition().y + BALLHEIGHT >= SCREENHEIGHT)
            ballvely = ballvely * -1;
        // Scoring
        else if(sBall.getPosition().x <= 0)
        {
            p2Score++;
            ballvelx = 0.75;
            ballvely = 0;
            sBall.setPosition(SCREENWIDTH/2 - (BALLWIDTH/2) , SCREENHEIGHT/2 - (BALLHEIGHT/2));
            std::cout << "Player 2 Scores!" << std::endl;
        }
        else if(sBall.getPosition().x + BALLWIDTH >= SCREENWIDTH)
        {
            p1Score++;
            ballvelx = -0.75;
            ballvely = 0;
            sBall.setPosition(SCREENWIDTH/2 - (BALLWIDTH/2) , SCREENHEIGHT/2 - (BALLHEIGHT/2));
            std::cout << "Player 1 Scores!" << std::endl;
        }
        // Ball/Paddle Collision
        else if(sBall.getPosition().x <= 30 &&
                sBall.getPosition().y + BALLHEIGHT >= sPaddle.getPosition().y &&
                sBall.getPosition().y <= sPaddle.getPosition().y + PADDLEHEIGHT)
        {
            bpdelta = (sBall.getPosition().y + BALLHEIGHT) - sPaddle.getPosition().y;
            std::cout << "BPDelta: " << bpdelta << std::endl;
            ballvelx = ballvelx * -1;
            if(bpdelta < 60)
            {
                ballvely = 1 / (bpdelta / 10);
                std::cout << "Delta <= 60" << std::endl;
                std::cout << ballvely << std::endl;
                if(ballvely > 0)
                    ballvely = ballvely + -1;
            }
            else if (bpdelta > 60)
            {
                bpdelta = bpdelta - 60;
                ballvely = bpdelta / 100;
                std::cout << "Delta > 60" << std::endl;
                std::cout << ballvely << std::endl;
            }
            else
                ballvely = 0;
        }
        // Ball/Computer Logic
            if(sBall.getPosition().x + BALLWIDTH >= SCREENWIDTH-PADDLEWIDTH &&
               sBall.getPosition().y + BALLHEIGHT >= sComputer.getPosition().y &&
               sBall.getPosition().y <= sComputer.getPosition().y + PADDLEHEIGHT)
            {
                bpdelta = (sBall.getPosition().y + BALLHEIGHT) - sComputer.getPosition().y;
                std::cout << "Computer Collide" << std::endl;
                ballvelx = ballvelx * -1;
                    if(bpdelta < 60)
                    {
                        ballvely = 1 / (bpdelta / 10);
                        if(ballvely > 0)
                            ballvely = ballvely + -1;
                    }
                    else if (bpdelta > 60)
                    {
                        bpdelta = bpdelta - 60;
                        ballvely = bpdelta / 100;
                    }
                    else if (bpdelta == 60)
                        ballvely = 0;
            }


            // Ball Logic
        sBall.move(ballvelx, ballvely);

            // AI Logic
        if(sBall.getPosition().y + (BALLHEIGHT/2) < sComputer.getPosition().y + (PADDLEHEIGHT/2))
            sComputer.move(0, -0.25);
        else
            sComputer.move(0, 0.25);

            // Clock Work
        frameCounter += clock.restart().asSeconds();
        if(frameCounter >= switchFrame)
            frameCounter = 0;

            // Drawing Screen
        window.clear();

        window.draw(sBackground);
        window.draw(sComputer);
        window.draw(sPaddle);
        window.draw(sBall);

        window.display();
    }

    return 0;
}

SpriteManager.h


#ifndef SPRITEMANAGER_H_INCLUDED
#define SPRITEMANAGER_H_INCLUDED

#include <iostream>

class SpriteManager
{
private:
public:
    void loadSprites();
};


#endif // SPRITEMANAGER_H_INCLUDED

SpriteManager.cpp


#include "SpriteManager.h"

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

void SpriteManager::loadSprites()
{
    sf::Texture background;
    if(!background.loadFromFile("Board.png"))
        std::cout << "Could not load background." << std::endl;
    sf::Sprite sBackground;
    sBackground.setTexture(background);

    sf::Texture paddle;
    if(!paddle.loadFromFile("Paddle.png"))
        std::cout << "Could not load paddle." << std::endl;
    sf::Sprite sPaddle;
    sPaddle.setTexture(paddle);

    sf::Sprite sComputer;
    sComputer.setTexture(paddle);

    sf::Texture ball;
    if(!ball.loadFromFile("Ball.png"))
        std::cout << "Could not load ball." << std::endl;
    sf::Sprite sBall;
    sBall.setTexture(ball);
}

Excellent, that gives all the information needed.

In C++, there's something called a 'scope'. Variables only exist until the code's execution reaches the end of the scope that the variable was contained in.
Variables in one scope can be accessed from variables in a nested scope, but variables in a nested scope can't be accessed from the owning scope.
void myFunction()
{ //Start of scope A
     
     int variableInScopeA;
 
     { //Start of scope B
           
           int variableInScopeB;
           
           variableInScopeA = 27; //Fine. I can access variables from parent scopes.
           
     } //End of scope B
     
     variableInScopeB = 27; //Not fine. 'variableInScopeB' doesn't exist in this scope.
     
} //End of scope A

Since functions themselves are scopes, then you can't access a variable that's declared in one function in any other function.
You can only pass the variables in through parameters - either copying the value into a local variable, or using a reference variable that pretends it's the same variable.
void functionA()
{
     int myVariableInFunctionA = 357;
}
 
void functionB()
{
     myVariableInFunctionA = 777; //Error! 'myVariableInFunctionA' doesn't exist in functionB's scope.
}

Even if you created an identically named variable in 'functionB()', it'd just be a separate variable that happens to be named the same. It wouldn't really be the same variable.

That's problem one - accessing variables in different scopes.

Problem two is, variables get destroyed when they reach the end of the scope they are in.
So if I do this:
void myFunction()
{
    sf::Sprite mySprite;
    
    {
        sf::Texture myTexture;
        //...
        
        mySprite.setTexture(myTexture);
        
    } //<--- 'myTexture' gets destroyed here when it goes out of scope, so mySprite now has an invalid texture!

} //<--- 'mySprite' gets destroyed here, because it now goes out of scope.
So there are two problems:
1) How do you make sure 'mySprite' is accessible from the scope that your code wants to access it from?
2) How do you make sure 'myTexture' stays alive as long as, or longer than, 'mySprite' stays alive for?

First, you are creating a class already, so if you make 'mySprite' and 'myTexture' member-variables of that class, then that means both 'mySprite' and 'myTexture' will stay alive as long as that specific copy (called an 'instance') of that class stays alive.
class SpriteManager
{
    private:
    sf::Texture myTextureA; //The texture doesn't need to be accessed publicly in your specific code, only the sprite does.
    
    public:
    sf::Sprite mySpriteA;
};
Great! Now we can access 'mySpriteA' like this:
SpriteManager mySpriteManagerInstance;

mySpriteManagerInstance.mySpriteA.setPosition(...)
But we still need to make sure that the class loads the textures properly.
Classes have something called 'constructors'. Constructors are functions that are automaticly called just once, when an instance of a class gets created. Let's make one.
[code]class SpriteManager
{
    private:
    sf::Texture myTextureA; //The texture doesn't need to be accessed publicly in your specific code, only the sprite does.
    
    public:
    SpriteManager(); //The function name of a class constructors are identical to the name of the class itself.
    sf::Sprite mySpriteA;
};[/code]

[code]SpriteManager::SpriteManager()
{
    if(!myTextureA.load(...))
    {
        //Report the error and quit the program, or however your program wants to handle loading failures.
    }

    mySpriteA.setTexture(myTextureA);
}

Thank you so much, that helped me a lot!

The problem seems so obvious now :P

Glad to help!

Since functions are one scope, they also exist in a parent scope that is called the 'global' scope. You *can* put variables in the global scope:

int myGlobalVariable = 0;
 
void myFunction()
{
      int myLocalVariable; //A variable in the local scope of this function.
     
      myGlobalVariable = 200; //Accessing the variable in the global scope.
}
 
class MyClass
{
     public:
     int myMemberVariable; //A variable belonging to the scope of this class
};

To make it available to other files, you have to 'extern' it in a header file.

//MyGlobals.h
extern int myGlobalVariable; //Lets source files that #include this header become aware of the existence of the variable.
 
//MyGlobals.cpp
int myGlobalVariable = 0; //The actual variable.
 
//main.cpp
#include "MyGlobals.h"
 
void myFunction()
{
    myGlobalVariable = 357; //Works fine.
}

While this is available in C++, and while it's very convenient, it's actually a bad programming practice to get into except when used in extreme moderation. There are a number of ways it can bite you when your programs grow to larger sizes, so it's best to, when starting out programming, pretend that feature doesn't exist. mellow.png

After about a half hour of intense trouble shooting I have found out my simple error, sorry for this now useless bump :P

This topic is closed to new replies.

Advertisement