SFML community forums

Help => General => Topic started by: AlexxanderX on October 08, 2012, 07:23:42 pm

Title: AlexxanderX problems...
Post by: AlexxanderX on October 08, 2012, 07:23:42 pm
Another problem. I try to make a moving system but I have a probem: when the rectangle(player) fall down from the floor( big regtangle) and I move to right || left the player go in the floor and I don't know how to ressolve it.
Here is the code:
///////////////
/// Headers ///
///////////////
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>

///////////////

////////////
/// Code ///
////////////
int main()
{
    /////////////////////////
    // Declarare variabile //
    /////////////////////////
    sf::Vector2f playersize(50,50); // Marimea jucatorului
    sf::Vector2f floorsize(600,50); // Marimea platformei
    bool isPlaying = false; // Variabila de verificare a desfasurarii jocului
    int wWidth = 800;
    int wHeight = 600;
    /////////////////////////

    //////////////////////
    // Creare fereastra //
    //////////////////////
    sf::RenderWindow window(sf::VideoMode(wWidth,wHeight),"Moving System"); // Fereastra
    window.setVerticalSyncEnabled(true); // OpenGL VerticalSync
    //////////////////////

    /////////////
    // Fonturi //
    /////////////
        // Font general
    sf::Font font;
    if (!font.loadFromFile("resources/AGENTORANGE.ttf")) return -1;
    /////////////

    /////////////////////
    // Muzica & Sunete //
    /////////////////////
        // Muzica
            // Muzica de background
                // Background Music 1
//    sf::Music bcgmsc1;
//    if(!bcgmsc1.openFromFile("resources/backgroundmusic.ogg")) return -1;
//    bcgmsc1.play();

        // Sunete

    /////////////////////

    // Creare jucator
    sf::RectangleShape player;
    player.setSize(playersize);
    player.setOutlineThickness(3);
    player.setOutlineColor(sf::Color::Black);
    player.setFillColor(sf::Color::Blue);
    player.setOrigin(playersize / 2.f);


    ////////////
    // Mesaje //
    ////////////
        // Mesaj general
    sf::Text message;
    message.setCharacterSize(40);
    message.setFont(font);
    message.setPosition(100, 15);
    message.setColor(sf::Color::Red);
    message.setString("Moving System\n Space to try it!");
    ////////////

    //////////////////////////////////////
    // Viteza jucator si alte variabile //
    //////////////////////////////////////
    float playerSpeed = 200.f;
    float playerDownSpeed = 300.f;
    float playerDownSpeedT = 50.f;
    //////////////////////////////////////

    ///////////
    // Level //
    ///////////
    sf::RectangleShape floor1;
    floor1.setSize(floorsize);
    floor1.setOutlineThickness(2);
    floor1.setOutlineColor(sf::Color::Green);
    floor1.setFillColor(sf::Color::Black);
    floor1.setOrigin(floorsize / 1.f);
    ///////////

    /////////////
    // Actiune //
    /////////////
    sf::Clock clock; // Crearea ceasului( clock)
    while (window.isOpen())
    {
        sf::Event event;

        while (window.pollEvent(event))
        {
            // Metoda de inchidere
            if ((event.type == sf::Event::Closed) ||
               ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)))
            {
                window.close();
                break;
            }

            if((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space))
            {
                if(!isPlaying)
                {
                    isPlaying=true;
                    clock.restart();

                    // Resetare pozitii
                    player.setPosition(400,200);
                    floor1.setPosition(700,600);
                }
            }
        }

        if (isPlaying)
        {
            float deltaTime = clock.restart().asSeconds();

            // Miscarea jucatorului
                // Miscarea in Stanga
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && (player.getPosition().x > 0.f + 20))
            {

                sf::Vector2f pos = player.getPosition();
                player.move(-playerSpeed * deltaTime,0);
            }
                // Miscarea in Dreapta
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && (player.getPosition().x < wWidth - 20))
            {
                sf::Vector2f pos = player.getPosition();
                player.move(playerSpeed * deltaTime,0);
            }

            // Coliziunea in JOS si SUS
            if (!(player.getPosition().y > floor1.getPosition().y + floorsize.y / 2 - 105))
            {
                player.move(0, playerDownSpeed * deltaTime);
            }

            if (!(player.getPosition().x < floor1.getPosition().x + 24) || !(player.getPosition().x > wWidth - floor1.getPosition().x - 24) )
            {
                player.move(0, playerDownSpeedT * deltaTime);
            }

        }

        // Sterge fereastra
        window.clear(sf::Color::Yellow);

        // Afisare
        if(isPlaying)
        {
            window.draw(player);
            window.draw(floor1);
        }
        else
        {
            window.draw(message);
        }

        // Afisarea ecranul
        window.display();
    }

    return 0;
}
 

And here a screenshot:
(http://imageshack.us/a/img708/566/80087348.png)
Title: Re: Resolve code...
Post by: eXpl0it3r on October 08, 2012, 08:13:28 pm
By reading some tutorials on collision detection in your case you'd probably want AABB (Axis-Aligned Bounding-Box).
Also you should take more time to look into your code, make research on your own, read tutorials etc. instead of creating new topics whenever things just don't work right away.
We do gladly help but part of programming is finding mistakes and do research on your own, so you should also skill yourself in those categories. ;)
Title: Re: Resolve code...
Post by: AlexxanderX on October 09, 2012, 07:49:29 am
Yes, I want an AABB. I searched on net and foundet Box2D. Is good Box2D? And is work with SFML?
Title: Re: Resolve code...
Post by: eXpl0it3r on October 09, 2012, 09:22:13 am
Yes Box2D is good and it works with SFML, but since I feel that you're not very familiar with C++ and SFML I'd advise you against it for now and you're better of implementing AABB on your own, which is very easy with SFML, in fact you don't really need to implement it, but you can use sf::Rect::contains() or sf::Rect::intersects() functions. ;)
Title: Re: Resolve code...
Post by: AlexxanderX on October 09, 2012, 02:09:03 pm
Hmm, seem hard. I know only the base on C++ but I can learn and same with SFML. I will try to use your information and to see if can. Exist some tutorials about creating an AABB?
Title: Re: Resolve code...
Post by: eXpl0it3r on October 09, 2012, 03:52:33 pm
Do you even try to find some information or did you investigate the path I showed you with the sf::Rect? Or do you just wait until someone writes you a step by step explanation? :-\

if(sf::FloatRect(floor1.getPosition(), floor1.getSize()).intersects(sf::FloatRect(player.getPosition(), player.getSize())))
    std::cout << "Collision!!!!!111" << std::endl;
Title: Re: Resolve code...
Post by: AlexxanderX on October 09, 2012, 04:12:48 pm
I didn't wanted you to show me the code and yes, I read the information from sf::Rect and I was trying to implement in my code. I only asked if exist some tutorials...  :-[
This is what I maked:
sf::IntRect playerr(player.getPosition().x, player.getPosition().y, 50, 50);
            sf::IntRect floor1r(floor1.getPosition().x, floor1.getPosition().y, 600, 50);
            sf::IntRect intersectr;
            intersect = playerr.intersects(floor1r, intersectr);

            if (!intersect)
            {
                player.move(0, playerDownSpeed * deltaTime);
            }
  ;D

Modify: How to stop my shape, if don't touch another shape( the floor) he is falling down. I think to do a loop to verify every time if he is touching a shape but when running the code he froze when press space:
while (!sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize())))
            {
                player.move(0, playerDownSpeed * deltaTime);
            }

if (!sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize())))
            {
                do
                {
                    player.move(0, playerDownSpeed * deltaTime);
                } while (!sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize())));
            }

do
            {
                player.move(0, playerDownSpeed * deltaTime);
            } while (!sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize())));

Those(3) were my attempts with the loop. Att all 3 when pressed space the app frozen.
Title: Re: Resolve code...
Post by: AlexxanderX on October 09, 2012, 07:52:30 pm
Tryed and this but same result:
sf::IntRect playerr(player.getPosition().x, player.getPosition().y, 50, 50);
            sf::IntRect floor1r(floor1.getPosition().x, floor1.getPosition().y, 600, 50);
            bool col;
            col = floor1r.contains(player.getPosition().x, player.getPosition().y);
            // Coliziunea in JOS si SUS
            if ((!sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize()))) && !col)
            {
                player.move(0, playerDownSpeed * deltaTime);

            }
Please help, I really can't resolve this problem :(
Title: Re: Resolve code...
Post by: AlexxanderX on October 10, 2012, 03:59:46 pm
OFF: I see no help, but if noone no that is  ;D

I tryed to do this:
if (sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize())))
            {
                gameover=true;

            }

// Sterge fereastra
        window.clear(sf::Color::Yellow);

        // Afisare
        if(isPlaying)
        {
            window.draw(player);
            window.draw(floor1);
            window.draw(messagev);
            if (gameover)
            {
//                window.clear(sf::Color::Black);
                window.draw(msgover);
            }
        }
        else
        {
            window.draw(message);
        }

But nothing. Why?
Title: Re: Resolve code...
Post by: eXpl0it3r on October 10, 2012, 05:40:58 pm
I tryed to do this:
But nothing. Why?
Sorry I've no idea what the problem is. "But nothing" isn't really a useful problem description... :-\

Modify: How to stop my shape, if don't touch another shape( the floor) he is falling down. I think to do a loop to verify every time if he is touching a shape but when running the code he froze when press space:
Is my assumption right that you've no idea what you're doing?

Just sit down for a moment without the PC in front of you and think about this logically.
If nothing special is happening then the player will fall, thus this is the 'default' behavior and that should happen every frame iteration.
But if he hits the ground he shouldn't move anymore.

This logic then translates into something like this:
bool hit = false;
while(window.isOpen())
{
    // ...
    // Event handling
    // ...
    if(!hit)
    {
        player.move(player.getPosition().x, player.getPosition().y + dt * gravity_speed);
    }
    if(collision(player, floor))
    {
        hit = true;
        // reset players position to align with the floor
    }
   
    // draw stuff
}

This skill on how to translate ideas into code is what a programmer needs. If you're not that good in such translations then maybe you shouldn't use SFML already but learn more on how to program with some simpler applications...
Title: Re: Resolve code...
Post by: AlexxanderX on October 11, 2012, 02:10:10 pm
This I maked but I have problems stoping the player. So I can't figure out this
// reset players position to align with the floor
because when the player is falling down he can move to the left or right so I tryed with
player.move(player.getPosition());
but nothing happen( the player continue falling down).
if(fly)
            {
                player.move(0,playerDownSpeed * deltaTime);
            }

            if (sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize())))
            {
                fly=false;
                player.move(player.getPosition());
            }

You wroted
player.move(player.getPosition().x, player.getPosition().y + dt * gravity_speed);
and I translated for my code in
player.move(player.getPosition().x, player.getPosition().y + playerDownSpeed * deltaTime);
and when I run the code and press space my shape(player) didn't show...

OFF: I'm yound and I don't have so much time for programming and at school I learn only the base for C++.
Title: Re: Resolve code...
Post by: AlexxanderX on October 11, 2012, 06:21:22 pm
I thought to make this:
if(fly)
            {
                player.move(0,playerDownSpeed * deltaTime);
            }

            if (sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize())))
            {
                fly=false;
                black = true;
            }
window.clear(sf::Color::Yellow);

        // Afisare
        if(isPlaying)
        {
            window.draw(player);
            window.draw(floor1);
            window.draw(messagev);
            if (gameover)
            {
                window.clear(sf::Color::Black);
                window.draw(msgover);
            }

            if (black)
            {
                window.clear(sf::Color::Green);
            }
        }
        else
        {
            window.draw(message);
        }

        // Afisarea ecranul
        window.display();

But the green screen didn't appear. I tryed to put to the if statement where verify if press left and when I pressed left the screen gone green. I think the problem in my code is this:
sf::FloatRect(player.getPosition(), player.getSize()).intersects(sf::FloatRect(floor1.getPosition(), floor1.getSize()))
Title: Re: Resolve code...
Post by: AlexxanderX on October 12, 2012, 10:16:24 pm
Can help because I don't know any onther solutions in mind. In the documentation in the exemple is something like this:
 // Test the intersection between r1 and r2
 sf::IntRect result;
 bool b3 = r1.intersects(r2, result); // true
 // result == (4, 2, 16, 3)
And I tryed something like this:
sf::IntRect playerr(player.getPosition().x, player.getPosition().y, 50,50);
            sf::IntRect floor1r(floor1.getPosition().x, floor1.getPosition().y, 600,50);
            sf::IntRect result;
            bool b3 = playerr.intersects(floor1r, result); // true

            if (b3)
            {
                fly=false;
                black = true;
                std::cout << "collision";
            }
And nothing, on the console no "collision" message. I tryed when press the right arrow on console to show me "Right" and worked. So, I really dont't know where is the problem but I think is the condition.
Title: Re: Resolve code...
Post by: AlexxanderX on October 13, 2012, 10:16:55 am
Succes. I maked this from some tutorials:
bool intersectss (const RectangleShape & rect1, const RectangleShape & rect2)
{
    FloatRect r1 = rect1.getGlobalBounds();
    FloatRect r2 = rect2.getGlobalBounds();

    return r1.intersects(r2);
}
if (intersectss(player, floor1))
            {
                FloatRect a=player.getGlobalBounds();
                FloatRect b=floor1.getGlobalBounds();
                std::cout << "collision";
                player.move(player.getPosition().x,player.getPosition().y);
            }
But I have problems with
player.move(player.getPosition().x,player.getPosition().y);
I don't know how to stop him, move him to align with the floor because when he is fly( not collision) he can move to the left or right and I don't know how to make this. With the above function the player dissapear from window.

EDIT
I modified in this:
if (intersectss(player, floor1))
            {
                fly=false;
                FloatRect a=player.getGlobalBounds();
                FloatRect b=floor1.getGlobalBounds();
                std::cout << "collision";
                player.move(0, 0);
                std::cout << player.getPosition().x << " " << player.getPosition().y << "\n";
            }
and is working. Please tell me if need some modifications? And thanks for helping, more for no helping I thanks  ;D.

EDIT2
Now have the same problem like in the first image.  :-\ I will try with the function sf::Rect::contain to sse what I can. But I maked a good collision system  ;D
Title: Re: Resolve code...
Post by: AlexxanderX on October 14, 2012, 12:44:47 pm
I resolved in a method my problem  ??? . Now I want to implement a jump system but I don'y know how to do that :( . Please some help...
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on October 17, 2012, 07:40:28 pm
Still did nothing. I don't know how to do that  :'( . This what I tryed:
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && PlayerJump)
        {
            float jumpn = 0.f;
            while (jumpn < 30.f)
            {
                player.move(0.f,-moveDistance*updateTime/100.0);
                jumpn++;

            }

            PlayerJump = false;
        }
But when I click on UP the player go up automatly, because, I think, the app make to fast the while function and I need something to pause them some miliseconds...
Title: Re: AlexxanderX problems...
Post by: G. on October 17, 2012, 09:39:00 pm
Are you sure you know what's going on with your while? It's basic C++ (or algorithm), you should learn the basics before attempting more advanced things like games. ^^
float jumpn = 0.f;
while (jumpn < 30.f)
{
    player.move(0.f,-moveDistance*updateTime/100.0);
    jumpn++;

}
If you unfold this loop here's what you get :
float jumpn = 0.f;
player.move(0.f,-moveDistance*updateTime/100.0);
jumpn++;
player.move(0.f,-moveDistance*updateTime/100.0);
jumpn++;
[... 30 times total ...]
player.move(0.f,-moveDistance*updateTime/100.0);
jumpn++;
player.move(0.f,-moveDistance*updateTime/100.0);
jumpn++;
Which is also equal to :
float jumpn = 0.f;
player.move(0.f,(-moveDistance*updateTime/100.0) * 30);
jumpn += 30;
I'm sure you'll notice what's going wrong here.


eXpl0it3r, thanks, I haven't even noticed that I was using quotes instead of code. :/
Title: Re: AlexxanderX problems...
Post by: eXpl0it3r on October 17, 2012, 10:31:00 pm
@G. please don't use quotes for displaying code, but make use of the code=cpp tag... ;)

It's basic C++ (or algorithm), you should learn the basics before attempting more advanced things like games.
Yes that's exactly why I haven't answered here anymore...

You're lacking major basic knowledge in basic concepts, some aren't even related to C++ or SFML directly but are plain logical ones (like the one G. illustrated). That's also why I told you to sit down and really think about what you're trying to do and then implement it and not just write something and hope it would work as you want it to and if it doesn't come here and post the problem... :-\
Learn more about C++ and try to read some code of other people and make sure you understand every little detail.

But since you've been stuck for so long and I kind of see that you're try to, I've written a small example, where you can move around a block, collide with the floor and the box and you can jump. Keep in mind it's an example and not production code, it should give you an example you can read and understand into its last detail.
And I don't want to hear the question at all how one would go about fixing the 'teleporting' problem when bumping into the box, that's for you to figure out. ;)

#include <SFML/Graphics.hpp>

int main()
{
    // Create window
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML");
    // Limit framerate
    window.setFramerateLimit(60);

    // Keep track of the frametime
    sf::Clock frametime;

    // Big floor
    sf::RectangleShape floor(sf::Vector2f(800.f, 40.f));
    floor.setPosition(0.f, 560.f);
    floor.setFillColor(sf::Color(10, 180, 30));

    // Small box
    sf::RectangleShape box(sf::Vector2f(40.f, 40.f));
    box.setPosition(500.f, 480.f);
    box.setFillColor(sf::Color(10, 180, 30));

    // Moveable player
    sf::RectangleShape player(sf::Vector2f(40.f, 40.f));
    player.setOrigin(20.f, 20.f);
    player.setPosition(400.f, 40.f);
    player.setFillColor(sf::Color(10, 30, 180));

    // Player speed
    sf::Vector2f speed(0.f, 0.f);

    // Gravity value
    const float gravity = 980.f;

    // Check if we're touching any floor/box
    bool touching = false;

    while(window.isOpen())
    {
        // Get delta time for framerate depended movement
        float dt = frametime.restart().asSeconds();

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

        // Slow down horizontal speed
        if(speed.x > 6.f)
            speed.x -= 3.f;
        else if(speed.x < -6.f)
            speed.x += 3.f;
        else
            speed.x = 0.f;

        // Adjust vertical speed
        if(touching)
            speed.y = gravity;
        else if(speed.y < gravity)
            speed.y += 10.f;
        else if(speed.y > gravity)
            speed.y = gravity;

        // Horizontal movement
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            speed.x = 0;
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            speed.x = -120.f;
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            speed.x = 120.f;

        // Jumping
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && touching)
            speed.y = -300.f;

        // Move the player
        player.setPosition(player.getPosition().x + speed.x * dt, player.getPosition().y + speed.y * dt);

        // Check collision & position adjustment
        if(floor.getGlobalBounds().intersects(player.getGlobalBounds())) // Floor
        {
            player.setPosition(player.getPosition().x, floor.getPosition().y-player.getOrigin().y);
            touching = true;
        }
        else if(box.getGlobalBounds().intersects(player.getGlobalBounds())) // Box
        {
            player.setPosition(player.getPosition().x, box.getPosition().y-player.getOrigin().y);
            touching = true;
        }
        else // We're not colliding
            touching = false;

        // Render
        window.clear();
        window.draw(player);
        window.draw(box);
        window.draw(floor);
        window.display();
    }
}
 
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on December 18, 2012, 04:08:16 pm
Thanks for long help eXpl0it3r. I learned some more about C++( and now, at school ned to restart with C++ :D ). I revised your code and I think you know, because is only a test for what I needed, your app have sam bugs. I will restart making my 2D app :D
Title: Re: AlexxanderX problems...
Post by: eXpl0it3r on December 18, 2012, 04:22:41 pm
I revised your code and I think you know, because is only a test for what I needed, your app have sam bugs.
I guess you mean 'some bugs' right?

Yeah I know that and I've also mentioned it. ;)
Keep in mind it's an example and not production code, it should give you an example you can read and understand into its last detail.
And I don't want to hear the question at all how one would go about fixing the 'teleporting' problem when bumping into the box, that's for you to figure out. ;)

Good luck!
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on December 18, 2012, 09:36:14 pm
Thanks! Now I resolved about the collision I want to know about principles of SideScrolling( I'm interested in how can move the map( the map is moving?) and I need to create from the start the all map?)
Title: Re: AlexxanderX problems...
Post by: G. on December 18, 2012, 10:09:27 pm
You don't move the map, you move the camera (the view).
Check the wiki for more info on sf::View (https://github.com/SFML/SFML/wiki/Tutorial%3A-Using-View).
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on December 20, 2012, 07:18:52 pm
Thanks :D .

I created a menu and I want to know if I maked good and what I need to improve:
#include<SFML/Graphics.hpp>
using namespace sf;

int main()
{
    RenderWindow window(VideoMode(800, 600), "MENU");
    window.setMouseCursorVisible(false);

    //  Meniul
    //      Fontul
    Font font;
    if(!font.loadFromFile("resurse/cbb.ttf")) return -1;

    float x = -10;
    //      Textele
    Text txtstartgame;
    short btxtstartgame = 1;
    txtstartgame.setFont(font);
    txtstartgame.setCharacterSize(50);
    txtstartgame.setColor(Color::Red);
    txtstartgame.setOrigin(x, -20);
    txtstartgame.setString("Start Game");

    Text txtoptions;
    short btxtoptions = 1;
    txtoptions.setFont(font);
    txtoptions.setCharacterSize(50);
    txtoptions.setColor(Color::Red);
    txtoptions.setOrigin(x, -60);
    txtoptions.setString("Options");

    Text txtexit;
    short btxtexit = 1;
    txtexit.setFont(font);
    txtexit.setCharacterSize(50);
    txtexit.setColor(Color::Red);
    txtexit.setOrigin(x, -100);
    txtexit.setString("Exit");

    short vstartapp = 1;

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

            if ((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Down))
            {
                if (btxtstartgame == 1)
                {
                    txtstartgame.setColor(Color::Red);
                    txtoptions.setColor(Color::Green);
                    btxtstartgame = 0;
                    btxtoptions = 1;
                }
                else if (btxtoptions == 1)
                {
                    txtexit.setColor(Color::Green);
                    txtoptions.setColor(Color::Red);
                    btxtexit = 1;
                    btxtoptions = 0;
                }
            }

            if ((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Up))
            {
                if (btxtoptions == 1)
                {
                    txtstartgame.setColor(Color::Green);
                    txtoptions.setColor(Color::Red);
                    btxtstartgame = 1;
                    btxtoptions = 0;
                }
                else if (btxtexit == 1)
                {
                    txtexit.setColor(Color::Red);
                    txtoptions.setColor(Color::Green);
                    btxtexit = 0;
                    btxtoptions = 1;
                }
            }
        }

        if (vstartapp == 1)
        {
            txtstartgame.setColor(Color::Green);
            vstartapp = 0;
        }

        window.clear();
        window.draw(txtstartgame);
        window.draw(txtoptions);
        window.draw(txtexit);
        window.display();
    }


}
 
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on January 17, 2013, 06:47:47 pm
After creating my physic system I mitted with this error: every frame my game verify for collision from a dynamic lists of floor( only the floor wich I can touch) and game work properly, but when I start my game( debug mode) the game make collision with a floor. I verified the proprietes of that floor( floor is an sf::Sprite vector) and my console give me those results:
Quote
maps.floor[1] top:4.51608e-039 left:2.51749e-009 width:1.85831e+028 height:1.19468e-038
...and here is the code:
// every frame create the map
void Maps::display(RenderWindow &window, int &level)
{
    int floorn = 0;
    for (int row=0; row<map_y; row++)
    {
        for (int col=0; col<map_x; col++)
        {
                if (mapn[row*map_x+col] != -1)
                {
                    //if (mapn[row*map_y+col] == 0) std::cout << "row(" << row << ")*map_y(" << map_y << ")+col(" << col << ") =>" << row*map_y+col << "\n";
                    floor[floorn] = _mapsprites[mapn[row*map_x+col]];
                    floor[floorn].setPosition(col * 64, row * 64);
                    std::cout << "maps.floor[1] top:" << floor[1].getGlobalBounds().top << " left:" << floor[1].getGlobalBounds().left << " width:" << floor[1].getGlobalBounds().width << " height:" << floor[1].getGlobalBounds().height << "\n"; // here I verify
                    window.draw(floor[floorn]);
                    floorn += 1;
                    floor.resize(floorn+1);
                }
        }
    }
}

//the function where all lead and go
Game::Game(sf::RenderWindow &window)
{
    int level = 1;
    Player player(level);
    Maps maps(level);
    speed.x = 0.f;
    speed.y = 0.f;
    p_s_moving = 0; // player_state_moving
    p_s_jumping = 0;
    p_coll_floor = 0;
    p_pos = player.player.getPosition();


    Clock clock, test;
    while (window.isOpen())
    {
        processEvents(window);
        dt = clock.restart().asSeconds();
        /* FOR FUTURE TEST */ //std::cout << "dt:" << dt << std::endl; /*T*/
        update(maps, player);
        window.clear();
        maps.display(window, level);
        window.draw(player.player);
        window.display();
    }
}

//function whee verify
void Game::update(Maps &maps, Player &player)
{
    p_moving(player);
    int i;
    sf::FloatRect f_player(p_pos.x, p_pos.y, 50, 50);
    int nfloor;
    float PlusY = 0, PlusX = 0;
    //std::cout << "p:" << player.getGlobalBounds().top << "\n";
    if (checkCollisionFloor(player, nfloor, maps))
    {
        if (player.player.getGlobalBounds().top + player.player.getGlobalBounds().height > maps.floor[nfloor].getGlobalBounds().top)
            PlusY = (player.player.getGlobalBounds().top + player.player.getGlobalBounds().height) > (maps.floor[nfloor].getGlobalBounds().top/2) ?
                -(player.player.getGlobalBounds().top + player.player.getGlobalBounds().height - maps.floor[nfloor].getGlobalBounds().top):
                0;
        if (((f_player.left + f_player.width) < maps.floor[nfloor].getGlobalBounds().left || (f_player.left + f_player.width) > maps.floor[nfloor].getGlobalBounds().left) && (player.player.getGlobalBounds().top + player.player.getGlobalBounds().height == maps.floor[nfloor].getGlobalBounds().top + maps.floor[nfloor].getGlobalBounds().height))
            PlusX = (f_player.left + f_player.width) < maps.floor[nfloor].getGlobalBounds().left ?
                (maps.floor[nfloor].getGlobalBounds().left + maps.floor[nfloor].getGlobalBounds().width) - f_player.left : (f_player.left + f_player.width) - maps.floor[nfloor].getGlobalBounds().left;
        speed.y = 0;
    }
    else
    {
        std::cout << "NOINTERSECTED" << i << "\n";
        if (((player.player.getGlobalBounds().top + player.player.getGlobalBounds().height)!=maps.floor[nfloor].getGlobalBounds().top) && !(((player.player.getGlobalBounds().left + player.player.getGlobalBounds().width) > (maps.floor[nfloor].getGlobalBounds().left + maps.floor[nfloor].getGlobalBounds().width)) || (player.player.getGlobalBounds().left < maps.floor[nfloor].getGlobalBounds().left)))
            speed.y = 160;
        //p_pos += sf::Vector2f(speed.x * dt, speed.y * dt);
        //return;
    }
    player.player.setPosition(player.player.getPosition().x + speed.x * dt + PlusX, player.player.getPosition().y + speed.y * dt + PlusY);
}

//checkCollision function
bool Game::checkCollisionFloor(Player &player, int &nfloor, Maps &maps)
{
    nfloor = 0;
    for (int i=0; i<(int)maps.dynamic_floor.size(); i++)
    {
        if (intersects(player.player, maps.floor[maps.dynamic_floor[i]]))
        {
            nfloor = i;
            return true;
        }
    }
    return false;
}
Title: Re: AlexxanderX problems...
Post by: masskiller on January 18, 2013, 05:06:21 am
Could you describe your problem a bit better. I hardly understood what was wrong.

You could also consider using a tile-map class, there are two (I think) in the wiki.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on January 20, 2013, 02:47:55 pm
I resolved my problem: I was first updating and after drawing :D
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on June 27, 2013, 01:52:51 pm
Hello. I have another problem that I can't resolve it:
(http://img32.imageshack.us/img32/511/dmad.png)
The timer("47") is setted to the 0,0 and no origin setted( so default 0,0) and how can see from image the y coord is wrong. Same bug and for the coords text(blue text) which is setted to 1,1 and again the y coord is wrong. Please some help, why the y coords is wrong? I tryed to change the font to Arial and after to Comic Sans MS but same bug.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on July 02, 2013, 09:06:59 am
Same problem... Please some help.

I created another project with this simple code - only font and text - https://gist.github.com/AlexxanderX/5907274 (https://gist.github.com/AlexxanderX/5907274) and I have the same bug: the text's y' coordonate is wrong. For this test I've used the Ubuntu-B font( to download: http://www.mediafire.com/download/4snkhqxly27noow/Ubuntu-B.ttf (http://www.mediafire.com/download/4snkhqxly27noow/Ubuntu-B.ttf))  Here is the results of running the above code: (http://img818.imageshack.us/img818/5833/pqqd.png)
Title: Re: AlexxanderX problems...
Post by: Laurent on July 02, 2013, 09:14:20 am
It looks right. What did you expect?
Title: Re: AlexxanderX problems...
Post by: Zeneus on July 02, 2013, 11:47:47 am
As Laurent said.. the code is correct and works..
The coordinates are (0,0) which is the correct position of the text..
If you dont CHANGE the y coordinate, it wont move vertically.. Thats why it seems wrong to you..
You have to change it ;)
Title: Re: AlexxanderX problems...
Post by: MadMartin on July 02, 2013, 02:14:33 pm
Perhaps it's a misunderstanding about the y-coordinates?
In SFML, y = 0 is at the top, while it can be at the bottom in other libs etc.
Title: Re: AlexxanderX problems...
Post by: cpolymeris on July 02, 2013, 02:35:08 pm
I think AlexxanderX means the text isn't aligned to the top of the window, but that is just because the font has some "headroom". Actually, what bothers me more is the often poor kerning, but that might, too, be the font's fault:

(http://i.imgur.com/updAbcO.png)

EDIT: That said, firefox manages to render it much better (http://paxgame.sourceforge.net/cgi-bin/fossil/index).
Title: Re: AlexxanderX problems...
Post by: Laurent on July 02, 2013, 04:52:31 pm
Quote
Actually, what bothers me more is the often poor kerning, but that might, too, be the font's fault
SFML applies kerning correctly for each pair of characters, so yes it might be the font.

Quote
That said, firefox manages to render it much better.
Hum, I don't see any major difference.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on July 05, 2013, 11:05:48 am
Yea, the font was the fault!

Now have another problem:
Handler::Handler()
{
window.create(sf::VideoMode(800,600),"SpeedCuber Challenge");
window.setFramerateLimit(60);
 
Menu menu(window);
Loading loading(window, menu.loadStages);
 
sf::Thread loadData(&Menu::loadData,&menu);
 
stage = 0;
 
loadData.launch();
while (window.isOpen())
{
//...
}
}

And I got those error:
Quote
[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
client: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed.
Aborted

So I tried to call XInitThreads() and I got those error:
Quote
XIO: fatal IO error 11 (Resource temporarily unavailable) on X server ":0"
after 86 requests (86 known processed) with 1 events remaining.
Failed to retrieve the screen configuration while trying to get the desktop video modes
Failed to get the window attributes
[xcb] Unknown sequence number while processing reply
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
client: ../../src/xcb_io.c:635: _XReply: Assertion `!xcb_xlib_threads_sequence_lost' failed.
Aborted

Those errors are errors from running, not from compiling!
Title: Re: AlexxanderX problems...
Post by: Laurent on July 05, 2013, 11:08:42 am
I have no idea, sorry. Calling XInitThread() usually works fine and solves this kind of errors.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on July 05, 2013, 11:14:23 am
I tryed to put XInitThreads in first line:
Handler::Handler()
{
     XInitThreads();
     //...
}
And I got those errors, but I tried to put after I create the window and worked, somehow. Now it's freeze - can't close, nothing happen.

This is a common problem( with threads) on Linux?
Title: Re: AlexxanderX problems...
Post by: Laurent on July 05, 2013, 11:35:08 am
No, as I said usually everything works fine.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on September 06, 2013, 08:10:03 am
Reinstalled linux and followed this link (http://en.sfml-dev.org/forums/index.php?topic=9808.0) for installind dependencies, but when running 'sudo make' i got this warning:
[ 36%] Building CXX object src/SFML/Window/CMakeFiles/sfml-window.dir/Linux/JoystickImpl.cpp.o
/home/alexxanderx/Work/Programare/Libraries/SFML-2.1/src/SFML/Window/Linux/JoystickImpl.cpp: In static member function ‘static bool sf::priv::JoystickImpl::isConnected(unsigned int)’:
/home/alexxanderx/Work/Programare/Libraries/SFML-2.1/src/SFML/Window/Linux/JoystickImpl.cpp:123:51: warning: ignoring return value of ‘ssize_t read(int, void*, size_t)’, declared with attribute warn_unused_result [-Wunused-result]

 
Title: Re: AlexxanderX problems...
Post by: Laurent on September 06, 2013, 08:18:00 am
Yes, I know. You can ignore it.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on September 06, 2013, 09:26:22 am
Thanks for fast replay :D

When try to run a compiled code I get this error:
./test: error while loading shared libraries: libsfml-graphics.so.2: cannot open shared object file: No such file or directory
 
[/s]

EDIT: resolved :D
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on October 03, 2013, 01:07:54 pm
I have a question not about SFML: I want to add to my game a resolution changer but I don't really know how to do with my background: my idea is to take an image with hight resolution( e.g. 2560x1980) and for smaller resolutions than the image to cut the image in rects( 1 rect size = max texture size) and after to scale it to feet the screen. Is good my idea? For lower resolutions as 800x600 will not take too much time to do this?

-resolved-
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on May 02, 2014, 09:22:19 am
Started creating a app which get the pixels from an image( webcam) and send to a host/server and the host recreate the image and show it on an RenderWindow. The client send packets of maximum 1000000~=1MB and send them to host. The host get almost of them and put them in a vector. The problem is that when the host tries to unpack the second packet the app crash with segmentation fault. Here is the code:
(click to show/hide)
After I get the output of packets size and "No more packets!..." and start the unpaching funtion it only shows: "Unpack the packet #1... end of packet..." and get segmentation fault:
Received 999988 bytes
Received 999988 bytes
Received 61440 bytes
No more packets! Received 3 packets!
Unpack the packet #0... end of packet...
./run: line 3:  5283 Segmentation fault      ./host
Title: AW: AlexxanderX problems...
Post by: eXpl0it3r on May 02, 2014, 09:48:25 am
Run it through a debugger and get the call stack where it's crashing.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on May 22, 2014, 04:10:12 pm
Thanks eXpl0it3r.

Sometimes when I run my app( and not only) the window, I think the view is not adjusted: the click position is wrong( for elements of SFGUI) and texts positions are not displayed at the correct position( on another project with no SFGUI). This happens only sometimes at the runtime of the app, sometimes when run the app everything works good. I can't show the code because is a huge code, but what I can provide is that I don't change the view of window and only create the window. Here is a video of the bug: https://www.youtube.com/watch?v=bUi_M_8xdWs&feature=youtu.be
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on September 06, 2014, 02:23:46 pm
I have a problem with my game: it's flickering( i don't know is the perfect word for my problem). I'm using Thor for animate my player and whenever I move the tiles are moved:
(click to show/hide)
But when I don't move the player everything is normal:
(click to show/hide)
This happen only when a draw everything to a sf::RenderTexture and after to the window:
m_scene.clear();
m_scene.draw(...)
m_scene.display();

sf::Sprite spriteScene(m_scene.getTexture());
window.draw(spriteScene);
When I draw directly to the window everything works fine.

I can't post the code, but trying to create an example code( until now I have not managed to remake the bug).
If you have some thoughts about how to resolve or from where it come the bug, please post.

I'm using the last version of SFML from GitHub.
Title: Re: AlexxanderX problems...
Post by: eXpl0it3r on September 13, 2014, 10:50:01 pm
Use integer numbers for your view moving and make sure all your tiles are on integer coordinates.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on September 14, 2014, 04:12:30 pm
Wow... using a simple trick:
view.setCenter(sf::Vector2f(sf::Vector2i(playerCenter));
the problem is resolved. Thanks a lot! ;D
Title: Re: AlexxanderX problems...
Post by: dabbertorres on September 14, 2014, 07:48:10 pm
That works, yes, but, I'd personally use something like this:
view.setCenter(std::floor(playerCenter.x), std::floor(playerCenter.y));
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on February 08, 2015, 08:58:39 pm
I have Linux Mint 17.1 and Mesa Mesa 10.1.3(stable) and when run an app is a frozen transparent window. The green circle example also doesn't work.

I have downgraded from Mesa 10.6.0-devel in the hope of resolving the problem and after reboot I have rebuilt the sfml and straight forward I have compiled the green circle example and it was working. But then I have rebuilt the Thor library and after that I compiled a project and the frozen transparent window appeared. And I go back to recompile the green circle example and the same frozen transparent window showed. Please some help.
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on February 17, 2015, 03:25:30 pm
I have the following code for the camera of my game:
// Updating the player
m_player.update(frame, m_quadTree);

// Getting the center position of the player
sf::Vector2f playerCenter = m_player.getCenter();

// Setting the center of the map(show only visible tiles)
m_map.setPlayerCenter(playerCenter);

// Setting the view to the center of the player
m_view.setCenter(std::floor(playerCenter.x), std::floor(playerCenter.y));

The problem is that when I jump only on vertical axis( only up arrow) the tiles are like trembling, and when i jump on diagonals( up arrow + left/right arrow) also the player start to tremble. Some tips please?

Here is a video with the problem:

https://www.youtube.com/watch?v=S9fzD4eJ5IA

EDIT: Setting the view center to the exact position resolv the problem, but also activate another problem discussed here.
EDIT2: Problem resolved: the player position is now also set with std::floor()
Title: Re: AlexxanderX problems...
Post by: eXpl0it3r on February 17, 2015, 05:27:10 pm
I don't really see the problem. Since you move the screen at the same time as your player moves, every slight change will apply to the screen as well.
What you might think about is to have a certain rectangle in which the player can move freely without moving the screen. Though that might still cause the "trembling" I fail to see. :D
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on February 19, 2015, 03:22:37 pm
The problem was from the player: I was not setting his position to an integer one. Thanks for tip :D
Title: Re: AlexxanderX problems...
Post by: AlexxanderX on July 21, 2015, 06:04:14 pm
Hello :D I have a problem: I'm getting high CPU usage with this code and I don't know what I'm doing wrong:
#include <SFML/Graphics.hpp>

int main()
{
        sf::RenderWindow window({800, 600}, "My window");

        sf::Time m_timePerFrame = sf::seconds(1.0f / 60.0f);
        sf::Time m_timeSinceLastUpdate = sf::Time::Zero;

        sf::Clock m_clock;
    while (window.isOpen())
    {
                sf::Time m_frame = m_clock.restart();
                m_timeSinceLastUpdate += m_frame;

                while (m_timeSinceLastUpdate >= m_timePerFrame)
                {
                        sf::Event event;
                while (window.pollEvent(event))
                {
                    if (event.type == sf::Event::Closed)
                        window.close();
                }

                        m_timeSinceLastUpdate -= m_timePerFrame;
                }

                window.clear();

                window.display();
    }

    return 0;
}

If instead of all the manual frame limiting I use window.setFramerateLimit(60) everything works fine - 0% cpu usage, but with my above code I'm getting high CPU usage. Please some help.
Title: Re: AlexxanderX problems...
Post by: kitteh-warrior on July 21, 2015, 06:22:59 pm
If you don't instruct the system to wait, would you expect it to? ;)
Use the sf::sleep to let the thread wait.
Title: Re: AlexxanderX problems...
Post by: Jesper Juhl on July 21, 2015, 07:34:42 pm
Window.setFramerateLimit(60);
That's the solution. What more to say?
If you ask the CPU to work as had as it can then it will. If you ask it to take some breaks it will. It's really simple.