Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - Canvas

Pages: 1 [2] 3
16
General / How to structure a SFML game?
« on: June 19, 2014, 03:33:51 pm »
Hello there fellow SFML users,

This is going to be a big question so get ready. First off I have attempted to create quite a few games with C++ and SFML, programming the functionality isn't to hard, but after a few weeks, or months or even days my structure does always seem to mess up, what I mean by that is, due to something I did way back means i have to amend something new to fix that problem but some of my old functions are using that function, this happens all the time and I completely understand it is my fault for not fully understanding the structure of my game or the program.

So basically I am trying to create a simple clone of Mario Bros, so we have a title screen, a character, some enemies, a map made of blocks, score, time, lives, levels, continues, projectiles etc. So here is the my problem, using SFML i have myself a imageService, soundService and musicService, now these basically just load a file and store it inside of a map so I can call on that file when I need. But here is the main problem

I have a State which has a ImageService, the state has a hero and a level, would I assign them each a image? for example hero.sprite = imageService.images["heroImg"]; would that be the best way? Second lets say if a level had some blocks, but some blocks are infront of the hero, would I have to write out my render function to say

//Draw level blocks

//Draw hero

//Draw upper level blocks

//Draw menu

//etc...
 

But then a really big important part is, the renderwindow is 800 by 600, in most computer games the user is allowed to change the size of the game, so lets say the user wants to display 1280 by 768, where would be the best place to draw the sprites differently? What about collision detection? if the view was 800 by 600 and now it is 1280 by 768 the width has go up by 1.5 and a bit and the height has changed by 168 pixels, would I save a global variable in my state which has the "ratios" of the screen? so 800 by 600 = 1:1 and 1280 by 768 = 1.6:1.28 would I then use that to modify all sprites displaying and also use that to modify collision detection?

I'm just really trying to get my head around the structure of a game, does anyone have any simple links to books or articles on how to structure one, or even better a tutorial on how to structure a simple SFML game.

17
Graphics / Create 2D torching lighting effect overlay
« on: May 26, 2014, 09:52:56 pm »
Hello there people,

I'm creating a dungeon crawler using SFML (of course), and basically I want to try and create a simple torch effect that is over the screen which will change in size, and brightness (alpha). At the moment I have a simple image which is just very dark yellow on the outsides and slowly goes transparent. At the moment my code looks a like this

overlayFaderSizeChange++;

                if (overlayFaderSizeChange == 10)
                {
                        sf::Color overlayColor = overlayFader.getColor();
                        overlayColor.a = rand() % 10 + 245;
                        overlayFader.setColor(overlayColor);

                        float randomValue = rand() % 100;
                        randomValue = randomValue / 5000;
                        overlayFader.setScale(1 + randomValue, 1 + randomValue);

                        overlayFaderSizeChange = 0;
                }

This as an effect, but it is so shuttle you don't really see the effect. Now I know this is kinda down to personal preference, but does anyone have a better idea on how to achieve this in my 2D world? Advice is also very good :)

18
General / Game structure help
« on: May 10, 2014, 04:30:02 pm »
I'm in the early stages of a game I would love to create and i'm trying to work out how the game program should be structured (classes, headers etc). I'm using C++ and SFML for this project.
Let me first by showing you my basic image of the structure. Don't pay attention to MainMenuState.cpp and NewGameState.cpp



Game.cpp will have an instance of all those services, it will also have the MainMenuState, NewGameState and LevelState. Now here is my problem.
Game.cpp will have a method that will call the RenderService.RenderWindow, I'm trying to work out exactly how I should code this method? Should I pass in an arrayList of sf::sprites? If I do this, the LevelState.cpp will need an ArrayList of sf::Sprites. which will be updated on each game step. But lets say the Hero.cpp has 1 sf::Sprite. the Map.cpp has 20 sf::sprites and Monster.cpp has 1 sf::Sprite. this would mean I have to pass 22 sf::Sprites back to the RenderService every game step (60fps). so that is 1320 sf::Sprites per second back to the RenderService. I understand game structure is a very hard thing to do and hard to implement correctly, because there isn't a "set" way. I have created a Vector which holds sf::Sprites and every time I call my Render function I clear the vector before so everything is removed for memory. This works fine. Would that be the answer? But as I stated before is passing a lot of sf::Sprites to be rendered ok?
 
Here is my simple SFML program to test this

#include <SFML/Graphics.hpp>
#include "ImageService.h"
#include "DisplayObject.h"
#include "Enums.h"
 
ImageService is;
DisplayObject displayObject;
 
int main()
{
        sf::RenderWindow window(sf::VideoMode(1024, 768), "SFML works!");
        sf::CircleShape shape(100.f);
        shape.setFillColor(sf::Color::Green);
 
        is.Images[image1].loadFromFile("ship1.tga");
        displayObject.sprite.setTexture(is.Images[displayObject.spriteType]);
        std::vector<sf::Sprite> displayObjects;
 
        while (window.isOpen())
        {
                displayObjects.clear();
                displayObjects.push_back(displayObject.sprite);
 
                sf::Event event;
                while (window.pollEvent(event))
                {
                        if (event.type == sf::Event::Closed)
                                window.close();
                }
 
                window.clear();
 
                window.draw(shape);
                //Draw out the selected sprites
                for (int i = 0; i < displayObjects.size(); i++)
                {
                        window.draw(displayObjects.at(i));
                }
 
                window.display();
        }
 
        return 0;
}

Let me know if you would like me to explain any part of my program

19
General / Mouse button press with mouse left checker is never true
« on: January 17, 2014, 08:58:45 pm »
Hello there SFML people,

I'm trying to do a simple left mouse button check event, but every time I use my left button on my mouse the if statement is never true :( can anyone see why in my code?

if (eve.type == sf::Event::MouseButtonPressed)
         {
            if (eve.mouseButton.button == sf::Mouse::Left)
            {
            result = true;
            }
         }

the if statement is copied from the 2.1 tutorials

Regards,

Canvas

20
Hello there people,

At the moment I have a simple std::vector<Object*> objects
Object is a custom class i have created which can be text, sprite, animated sprite etc etc.
Now in my GameState class the code is starting to get a little large and I was wondering If I can do this.

The objects variable is a vector of pointers to "Object"s. Is it safe for me to do the following.

Create a new class called "StateLoader"
StateLoader will then deal with setting up the objects for whatever the game state is in
and then return a std::vector<Object*>, is this a safe thing to do or not?

When I mean safe, if is ok to populate a vector of pointers, and then set a variable to be equal to that vector of pointers? I just want to populate my objects variable outside of my gamestate class as the class is getting abit large because of all the objects being set.

If anyone can shine some light onto this it would be great.

Regards,

Canvas

21
General / Store a made texture by the program for future use
« on: December 11, 2013, 10:42:57 pm »
Hello there people,

I'm trying to implement a custom car maker, well basically the player is given a 32 by 32 grid, which they can place 4 by 4 pixel blocks on like so

now this will be of course stored in a 2D array, now for this example lets state that we have a 2D array which can hold 4 by 4

int carDesign[3][3]

the player then designs their car by placing blocks, at the end the player has something like this

0,1,1,0
1,0,0,1
1,0,0,1
0,1,1,0

now we first step through the 2D array and draw a block every time we reach a 1
so the first row would be like
no block, block, block, no block
each row element is X position 4 * element number
each column element is Y position 4 * element number

so at the end we have something like so draw on the screen



now this is awesome, this is something that I want and I can implement without a problem but here is the my problem, later on the game the player can create a 128 by 128 car, the 2D array would have a total of 1024 blocks to check, and it would have to do that for loop every frame to draw this custom car, now this would eat up tons of process as I plan to allow 8 players via network to play together, and draw 8 of these is 8192 blocks to draw every frame.

So i'm wondering if we had a 32 by 32 car design which is stored in a 2D array, could we not step though the 2D array elements once, save the outcome in a texture, then I can call stick that texture into a sprite and use that sprite, this then becomes a 1 block step compared to a large 1024 for loop to draw the same image, I am thinking I could allow the program to save the outcome as a image file and then load that up, but I would prefer if I could store the image output into a texture in the program for later use, does anyone have any ideas on who I could do that?

Thank you for reading.

Canvas.

22
General discussions / SFML 2.0 C++ book questions
« on: December 02, 2013, 09:22:13 pm »
Hey there people,

I have purchases the SFML 2.0 book (a while ago), it is going great, but some pieces of code in the book i don't 100% understand. I'm hoping someone here can just help me out with some parts,

On page 57 there is this piece of code

        auto found = std::find_if(mChildren.begin(), mChildren.end(),
                [&] (Ptr& p) -> bool { return p.get() == &node; });

found is a auto variable which is?
i understand the std::find_if
but what does this line mean? [&] (Ptr& p) -> boo
and return p.get() == &node;???

I will also be asking more questions as I see them

23
General / Top Down car movement help
« on: September 23, 2012, 01:55:15 am »
Hey guys

I have a new question for you all, I'm trying to make a car that faces a direction, when the user holds W it will increase the speed, if S is held it will slow down the car, if A or D is held the car will turn in the right direction, so for example
Car is facing North (0 degrees)
Car speed is 4.
player holds D
carDirection += 5

so if the player is holding W and holding D the car will increase and start turning right, but will keep going round in circles and circles.

How can I implement this with SFML and C++???

Cheers

24
General / Weird sf::Font problem
« on: September 22, 2012, 05:00:09 pm »
Hey guys,

I'm trying to display some simple text and im getting weird errors, now this piece of code works
gEntity.h

#ifndef g_Entity_H
#define g_Entity_H

//includes
#include "g_Rec.h"
#include "g_Image_Manager.h"
#include <iostream>
#include <string>
//Game Includes
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>   

class gEntity{
    private:
    sf::Sprite tex;
        bool spr,txt,btn;
        rect pos;
        sf::Font fontStyle;
                sf::Text textDisplay;
    public:
    gEntity();
        void  setup(int id, gImageManager& imgManage);
        sf::Sprite rtnTex(){return tex;}
        bool rtnSpr(){return spr;}
        bool rtnTxt(){return txt;}
        bool rtnBtn(){return btn;}
        rect rtnPos(){return pos;}
        void intText(int set);
        void stringText(std::string set);
                sf::Text rtnText(){return textDisplay;}
};

#endif
 

//skip alot of the cpp file
 case 1:
                        {
                fontStyle.loadFromFile("arial.ttf");
                //textDisplay.setFont(fontStyle);
                textDisplay.setString("Booty Swag");
                textDisplay.setPosition(100,100);
                spr = false; btn = false; txt = true;
        break;
 

gState code just to draw stuff
for(int i = 0; i < entities.size(); i++ )
                {
                        if (entities.at(i).rtnBtn() == true)
                        {

                        }

                        if (entities.at(i).rtnTxt() == true)
                        {
                                screen.draw(entities.at(i).rtnText());
                        }

                        if (entities.at(i).rtnSpr() == true)
                        {
                                screen.draw(entities.at(i).rtnTex());
                        }
                }
 

now this works fine, but if i close my window sometimes it will stay status is 0 or a random number and throw a error as i close, and the other error is if i uncomment the line which sets the font style at the draw method for the rtnText it displays memory violation... im using SFML 2.0, can anyone help me out?

Cheers

25
General / Quick question about game states.
« on: September 18, 2012, 12:09:06 pm »
Hey guys,

I'm just enquiring what you guys would do, I'm making a small game but I'm not 100% sure on how I should code the states (main menu, new game, choose puzzle, puzzle level), I have a gState which will have the sf::View and sf::RenderWindow screen, gState will also check what is in use and return what sprites needs to be return't. But when a state is changed, should gState do all of the work, or should i make a cpp and h file for each state.
like so
mainMenu.cpp/.h
newGame.cpp/.h
choosePuzzle.cpp/.h
puzzleLevel.cpp/.h
or should gState have a enum which will deal with the different states?

I hope that is enough information.

Canvas

26
Graphics / Help Understanding this imageManager
« on: September 15, 2012, 02:19:08 pm »
Hey guys, ive been using this imageManager, now i can use it find and what not, but I dont "fully" understand it,  here is the header and cpp file

Everything with a //---// at the end i dont understand

imageManager.h
//Image manager header
#ifndef gIMAGEMANAGER_H
#define gIMAGEMANAGER_H
//Includes
#include <SFML/Graphics.hpp>
//Body
class gImageManager
{
public:
        gImageManager();
        ~gImageManager();

private:
        gImageManager( const gImageManager& ); //---//1a
        gImageManager& operator =( const gImageManager& ); //---//1b

public:
        const sf::Texture& get_image( const std::string& filename ); //---//1c

private:
        std::map< std::string, sf::Texture > images_;
        std::vector< std::string > resource_directories_;
};
//end body
#endif
 
1a = gImageManager passes a reference of another gImageManager???
1b = I have no idea with that function
1c = why does it use so many references? can i not just remove these?

imageManager.cpp
#include <map>
#include <iostream>
#include <SFML/Graphics.hpp>
#include "gImageManager.h"

gImageManager::gImageManager() : images_(), resource_directories_() //---//1a
{
}

gImageManager::~gImageManager() //---//1b
{
        images_.clear();
        resource_directories_.clear();
}

const sf::Texture& gImageManager::get_image( const std::string& filename )
{
        // Check, whether the image already exists
        for( std::map<std::string, sf::Texture>::const_iterator ci = images_.begin();
                 ci != images_.end();
                 ++ci)
        {
                if( filename == ci->first ) //---// 1c
                {
                        //std::cout << "DEBUG_MESSAGE: " << filename << " using existing image.\n";
                        return ci->second;
                }
        }
       
        // The image doesen't exists. Create it and save it.
        sf::Texture image;

        // Search project's main directory
        if( image.loadFromFile( filename ) )
        {
                images_[filename] = image;
                //std::cout << "DEBUG_MESSAGE: " << filename << " loading image.\n";
                return images_[filename];
        }

        /*// If the image has still not been found, search all registered directories
        for( std::vector< std::string >::iterator it = resource_directories_.begin();
                 it != resource_directories_.end();
                 ++it )
        {
                if( image.loadFromFile( (*it) + filename ) )
                {
                        images_[filename] = image;
                        //std::cout << "DEBUG_MESSAGE: " << filename << " loading image.\n";
                        return images_[filename];
                }

        }*/


        std::cout << "GAME_ERROR: Image was not found. It is filled with an empty image.\n";
        images_[filename] = image;
        return images_[filename];
}
 
1a = I just dont understand the : images_(), resource_directories_() after the gImageManager::gImageManager... what does that line do??? ": images_(), resource_directories_()"
1b = Im sure this is just the de-construction of the class, but im just making sure.
1c = ??? if it isnt the first item, then return the second item????

If anyone could just quickly explain these, it would be a great help :)

Canvas

27
General / sf::Text weird display?
« on: July 21, 2012, 05:01:27 am »
Hey there guys, ive got a small piece of code
tmpPos.x = 162; tmpPos.y = 34;
                                        tmpText.setUpText(tmpPos,"hair",font);
                                        tmpText.textDisplay.setColor(sf::Color(25,25,25));
                                        tmpText.textDisplay.setCharacterSize(38);
                                        texts.push_back(tmpText);
                                        tmpPos.x = 136; tmpPos.y = 141;
                                        tmpText.setUpText(tmpPos,"colour",font);
                                        tmpText.textDisplay.setColor(sf::Color(25,25,25));
                                        tmpText.textDisplay.setCharacterSize(38);
                                        texts.push_back(tmpText);
 

tmpText is made in the header file so its global to the class, now all this does it sets up a position and passed in a font and a string.
Here is my setUpText Method
void gText::setUpText(rect rectPos,string stringDisplay,sf::Font &font)
{
        timer = 0;
        alive = true;
        fontStyle = font;
        pos = rectPos;
        stringText.clear();
        stringText.insert(0,stringDisplay);
        textDisplay.setFont(fontStyle);
        textDisplay.setString(stringText);
        textDisplay.setPosition(pos.x,pos.y);
        std::cout << stringDisplay << std::endl;
}
 

now on my screen i get this

hair is = fi
colour = colour,

why is hair fi? i cleared the sf::Text but im just really confused on why it isnt the correct string i told it to be, anyone see my problem?

cheers

28
General / Left button mouse but odd behaviour :(
« on: July 20, 2012, 03:48:39 pm »
---FIXED---

Hey guys, i've just coded myself a very simple button system where you can change colours of a block, now it works but not 100%, if I hold my mouse over my block which is 40 by 40, and hold left click, it will add maybe 5 or 10 to red, but then stop, even if the mouse is still in collision with the block and im holding left click, what I would like it to do is just keeping adding red until I let go or the mouse isnt in collision with that block anymore.

here is my code for the colour adding

if(iEvent.type == sf::Event::MouseButtonPressed == true && iEvent.mouseButton.button == sf::Mouse::Left){leftMouseButton = true;}else{leftMouseButton = false;}
                if(leftMouseButton == true)
                {
                                for(int i=0;i<menuBtns.size();i++)
                                {
                                        if(math.pointInRect(sf::Mouse::getPosition(screen).x,sf::Mouse::getPosition(screen).y,int(menuBtns.at(i).pos.x),int(menuBtns.at(i).pos.y),menuBtns.at(i).pos.w,menuBtns.at(i).pos.h) == true)
                                        {
                                                switch(menuBtns.at(i).rtnID())
                                                {
                                                case 1:                 if(clickTimer == 0){clickTimer = 1; player.setHairId(player.rtnHairId()+1);}
                                                        break;
                                                case 2:                 if(clickTimer == 0){clickTimer = 1; player.setHairId(player.rtnHairId()-1);}
                                                        break;
                                                case 3: player.setColor('r',1); cout << "Red +1" << endl;
                                                        break;
                                                case 4: player.setColor('r',-1); cout << "Red -1" << endl;
                                                        break;
                                                case 5: player.setColor('b',1); cout << "Blue +1" << endl;
                                                        break;
                                                case 6: player.setColor('b',-1); cout << "Blue -1" << endl;
                                                        break;
                                                case 7: player.setColor('g',1); cout << "Green +1" << endl;
                                                        break;
                                                case 8: player.setColor('g',-1); cout << "Green -1" << endl;
                                                        break;
                                                }
                                        }
                                }
                }
 

the math.pointInRect is this piece of code
        bool pointInRect(int pnt_x, int pnt_y, int rect_x, int rect_y, int rect_w, int rect_h)
        {
        if ( (pnt_x >= rect_x) && (pnt_x <= rect_x + rect_w - 1) )
        {
                if ( (pnt_y >= rect_y) && (pnt_y <= rect_y + rect_h - 1) )
                {return true;}
        }
        return false;
        }
 

any reasons why it doesnt keep just adding?

ok for my code I have just changed this
if(math.rectTorectCollision(sf::Mouse::getPosition(screen).x,sf::Mouse::getPosition(screen).y,1,1,int(menuBtns.at(i).pos.x),int(menuBtns.at(i).pos.y),menuBtns.at(i).pos.w,menuBtns.at(i).pos.h) == true)
now it uses my rectTorectCollision which is this
        bool rectTorectCollision(int rect1_x, int rect1_y, int rect1_w, int rect1_h,
                                                                int rect2_x, int rect2_y, int rect2_w, int rect2_h)    
        {
if ( pointInRect(rect1_x, rect1_y, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
        if ( pointInRect(rect1_x + rect1_w - 1, rect1_y, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
        if ( pointInRect(rect1_x + rect1_w - 1, rect1_y + rect1_h - 1, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
        if ( pointInRect(rect1_x, rect1_y + rect1_h - 1, rect2_x, rect2_y, rect2_w, rect2_h) ){return true;}
        if ( pointInRect(rect2_x, rect2_y, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
        if ( pointInRect(rect2_x + rect2_w - 1, rect2_y, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
        if ( pointInRect(rect2_x + rect2_w - 1, rect2_y + rect2_h - 1, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
        if ( pointInRect(rect2_x, rect2_y + rect2_h - 1, rect1_x, rect1_y, rect1_w, rect1_h) ){return true;}
        return false;
        }
 
now if i hold left click it will keep adding red but if i move it will stop, how can i get it to keep going? :(
lol once again i have created a useless topic because i have fixed it once again...
in my rectorectcollision i put this at the top of my code

if(iEvent.type == sf::Event::MouseButtonPressed == true && iEvent.mouseButton.button == sf::Mouse::Left){leftMouseButton = true;}
                if(iEvent.type == sf::Event::MouseButtonReleased == true && iEvent.mouseButton.button == sf::Mouse::Left){leftMouseButton = false;}
 
it now works fine, it seems that when you press left click, after about a second it will just go back to 0, it seems the framerate would reset it, so now i just put another if statement and it works.

29
General / Vector of text but access violation
« on: July 18, 2012, 03:16:39 pm »
Hey guys, just a little problem.
I have a vector of a class called gText,
I know for a fact that gText works as i use it for something else, but i cant seem to get it to work in a different state...
this is my code for the working piece i already have

gText tempText;
tempText.setUpInt(monsters.at(i).pos,monsters.at(i).rtnDam(),font);
texts.push_back(tempText);
 

and in my draw method it draws it fine,

also pos is just a simple rect class i made, the rtnDam is just a int and font is a variable that holds a sf::Font

so i then put this code to draw some text on screen

                        gText tmpText;
                        rect pos;
                        pos.x = 200;
                        pos.y = 100;
                        pos.h = 1;
                        pos.w = 1;
                        tmpText.setUpText(pos,"text",font);
                        texts.push_back(tmpText);
 

now if i run any method from my gText class, i can return the text, i can also return its pos. but with this code

for(int i=0;i<texts.size();i++){if(texts.at(i).rtnAlive() == true){screen.draw(texts.at(i).rtnText());}}
 

i get a huge access violation error which im really confused about. can anyone tell me whats wrong?

Cheers.

Its ok, i found out it was going out of scope, and as i could access the string and pos, i still couldnt access the sf::text cause of how sfml is coded :), but i fixed it. cheers

30
Graphics / Check to show sprite function
« on: July 07, 2012, 06:29:39 pm »
Hey guys,
Its ok i found the solution myself, Now the probelm i am having is my fps is only 30 maybe 27, is that ok? i have 500 16 by 16 blocks every row and i have 300 columns, to create a 2D level. i have code to stop they showing their sprite if they are not on the screen

Pages: 1 [2] 3