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

Author Topic: SFML 2.0 and Box2d PRoblem  (Read 2923 times)

0 Members and 1 Guest are viewing this topic.

superzuman

  • Newbie
  • *
  • Posts: 2
    • View Profile
SFML 2.0 and Box2d PRoblem
« on: September 24, 2015, 07:33:18 pm »
Hello.
Sorry for my Ingles.Estoy trying to integrate Box2d in SFML 2.3, and I'm having trouble adding physical my character, which in this case would be a box.
The character appears and Showing the position by the command console does not fall by gravity, which could not be the error.
Personaje.h
#pragma once
#include <Box2D/Box2D.h>
#include <SFML/Graphics.hpp>


class Personaje
{
public:
        Personaje(b2World& World);
        Personaje();
        void run(sf::RenderWindow& window);
private:
        sf::Vector2f m_Size;
        b2Body *m_pBody;
        b2PolygonShape polyShape;
        b2FixtureDef fixtureDef;
        b2BodyDef bodyDef;
};

 
Personaje.cpp
#include "Personaje.h"
#include "config.h"
#include <stdio.h>

#define PPM 64.0f               //PIXELS POR METRO
#define MPP (1.0f/PPM)          //METROS POR PIXEL


Personaje::Personaje(b2World& world)
{
        m_Size = sf::Vector2f(50.0f, 50.0f);
       
        bodyDef.type = b2_dynamicBody;
        bodyDef.position.Set(50.0f, 50.0f);
        m_pBody = world.CreateBody(&bodyDef);

        polyShape.SetAsBox(50.0f/2*MPP, 50.0f/2*MPP);

        fixtureDef.shape = &polyShape;
        fixtureDef.friction = 0.2f;
        fixtureDef.restitution = 0.3f;
        fixtureDef.density = 0.7f;

        m_pBody->CreateFixture(&fixtureDef);

       
}

void Personaje::run(sf::RenderWindow& window)
{
       
        sf::RectangleShape person(m_Size);
        person.setOrigin(m_Size.x / 2, m_Size.y / 2);
        person.setFillColor(sf::Color::Green);

        float angle = m_pBody->GetAngle();
        b2Vec2 pos = m_pBody->GetPosition();

        person.setPosition(pos.x * PPM, pos.y * PPM);
        person.setRotation((angle * 180) / PPM);
        window.draw(person);

}
EscenarioPrueba.h
#pragma once
#include <SFML\Graphics.hpp>
#include <SFML\Audio.hpp>
#include "Box2D\Box2D.h"
#include "Personaje.h"
class EscenarioPrueba
{
public:
        EscenarioPrueba();
        void run();
private:
        sf::RenderWindow window;
        sf::Clock clock;
        sf::Time time;
       
       

};

 
EscenarioPrueba.cpp
#include "EscenarioPrueba.h"
#include "config.h"
#include "Box2D\Box2D.h"

#define TIMESTEP 1.0f/60.0f     //TIEMPO DE REFRESCO
#define VELITER 10              //NUMERO DE ITERACION POR TICK PARA CALCULAR LA VELOCIDAD
#define POSITER 10              //NUMERO DE ITERACIONES POR TICK PARA CALCULAR LA POSICION

#define PPM 64.0f               //PIXELS POR METRO
#define MPP (1.0f/PPM)          //METROS POR PIXEL

EscenarioPrueba::EscenarioPrueba()
{
       

       
}

void EscenarioPrueba::run()
{
        //Definir Mundo Box2D (El parametro es la gravedad)
        b2World world(b2Vec2(0.0f, 10.0f));

        //Definir Suelo Box2D
        b2BodyDef sueloBodyDef;
        sueloBodyDef.position.Set(400.0f*MPP, 550.0f*MPP);
        b2Body* sueloBody = world.CreateBody(&sueloBodyDef);
        b2PolygonShape sueloBox;
        sueloBox.SetAsBox(800.0f / 2 * MPP, 100.0f / 2 * MPP);
        sueloBody->CreateFixture(&sueloBox, 0.0f);
        // Crear ventana
    sf::RenderWindow window(sf::VideoMode(800, 600), "Prueba Box2D");
        window.setFramerateLimit(60); //Hacer que los tiempos de refresco casen con los tiempos de Box2D

       
        // Bucle del juego
    while (window.isOpen())
    {
        // Bucle de Eventos de ventana
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Cerrar la ventana cuando se pulsa en el boton de cerrar ventana
            if (event.type == sf::Event::Closed)
                window.close();
        }
 
        // Limpiar ventana con el color negro
        window.clear(sf::Color::Black);
 
                //Actulizar mundo Box2D
                world.Step(TIMESTEP, VELITER, POSITER);

                //Dibujamos a nuestro perosnaje principal
                Personaje personaje(world);
                personaje.run(window);

                // Dibujamos un rectangulo que actuara de suelo mas adelante
                sf::RectangleShape rectSuelo(sf::Vector2f(800, 100));
                rectSuelo.setOrigin(800 / 2, 100 / 2);
                rectSuelo.setPosition(sf::Vector2f(sueloBody->GetPosition().x*PPM, sueloBody->GetPosition().y*PPM));
                rectSuelo.setFillColor(sf::Color::Red);
                window.draw(rectSuelo); //Dibujamos el elemento en el buffer

                // Mostrar el buffer en pantalla
                window.display();
    }
}

 
main.cpp
#include "EscenarioPrueba.h"

int main()
{
        EscenarioPrueba escenarioPrueba;
        escenarioPrueba.run();

        return 0;
}
Thank you very much in advance for your help.

Jesper Juhl

  • Hero Member
  • *****
  • Posts: 1405
    • View Profile
    • Email
Re: SFML 2.0 and Box2d PRoblem
« Reply #1 on: September 24, 2015, 07:49:15 pm »
I have nothing to contribute regarding your problem - sorry.
But I just wanted to say that if you want other people to be able to help you and want as big a pool of people as possible, then you should consider using english names for variables, class names etc and using english in comments etc.
Like it or not, but english is the common language for programmers and not using it severely limits the number of people who can read/understand/help you with your code.
« Last Edit: September 24, 2015, 08:03:00 pm by Jesper Juhl »

DarkRoku12

  • Full Member
  • ***
  • Posts: 203
  • Lua coder.
    • View Profile
    • Email
Re: SFML 2.0 and Box2d PRoblem
« Reply #2 on: September 24, 2015, 08:10:53 pm »
Como mi idioma nativo es el español respondere en ambos idiomas, yo tengo buena experiencia con Box2D asi que puedes contactarme por MP si lo deseas.

Cuando llamas world.step() este se suele colocar a una frecuencia (1/60) que seria igual a 60 fps, significa que se actualizara a esa velocidad, para que box2d se actualize debes poner world.step() en el main loop, donde box2D hara los calculos cada frama (cuadro). Supongamos que estableces un limite de 60 fps window.setFrameLimit(60);

trata colocando esto en el main loop para que sea actualizado cada frama en vez de afuera:

        world.Step(TIMESTEP, VELITER, POSITER);
        personaje.run(window);


When we call world.step() this is often set at (1/60) that will be the same as 60 fps,meas that Box2Dwill update at this speed, for box2D get updates you need to put world.step() inside of the main loop, where box2D will do the math every frame. Supose that you set a frame limit of 60 fps
window.setFrameLimit(60) ;

try to put this on the main loop for be updated every frame instead of out:

        world.Step(TIMESTEP, VELITER, POSITER);
        personaje.run(window);
I would like a spanish/latin community...
Problems building for Android? Look here

superzuman

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: SFML 2.0 and Box2d PRoblem
« Reply #3 on: September 24, 2015, 08:31:49 pm »
En el código , esta puesto así:
world.Step(TIMESTEP, VELITER, POSITER);
Personaje personaje(world);
personaje.run(window);
pero no hace nada, ni siquiera aparece la caja,el word.step esta en el bucle principal , he seguido varios tutoriales de Box2D y nada.
Muchas gracias por la respuesta y es todo un de talle que este en español :)
In English:
In the code, so this post:
world.Step(TIMESTEP, VELITER, POSITER);
Personaje personaje(world);
personaje.run(window);
but does nothing, not even the box appears, the word.step this in the main loop, I followed several tutorials Box2D and nothing.
Thank you very much for the answer and it is a waist that is in Spanish :)

Jesper Juhl

  • Hero Member
  • *****
  • Posts: 1405
    • View Profile
    • Email
Re: SFML 2.0 and Box2d PRoblem
« Reply #4 on: September 24, 2015, 08:41:47 pm »
Could we stick to english please? This is an english language forum after all.

Hapax

  • Hero Member
  • *****
  • Posts: 3360
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: SFML 2.0 and Box2d PRoblem
« Reply #5 on: September 24, 2015, 08:44:58 pm »
They are, at least, providing the English translation as well.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

Jesper Juhl

  • Hero Member
  • *****
  • Posts: 1405
    • View Profile
    • Email
Re: SFML 2.0 and Box2d PRoblem
« Reply #6 on: September 24, 2015, 08:46:52 pm »
Yes, and that's great.
I just wish they would respect the fact that english is the language of this forum. But the translations are great and the reason why I don't care too much :-)

DarkRoku12

  • Full Member
  • ***
  • Posts: 203
  • Lua coder.
    • View Profile
    • Email
Re: SFML 2.0 and Box2d PRoblem
« Reply #7 on: September 24, 2015, 08:55:49 pm »
I will follow this conversation with private messages.

Probably the math inside the game logic is wrong, and the objects doesn't appear in the corrects positions.

To know this we can output the positions with std::cout, and test until we get what we want.

For testing is better being minimal, less abstractions as be posible.

Taking in account that we had to considerates the relations, i use for box2d *0.1  when passing position (sfml to box2d) (x,y) and use *10 when getting position (box2d to sfml) .

In rotation i use this #defines

#define TO_RAD 0.0174532925199432957f 
#define TO_DEGREES 57.295779513082320876f
« Last Edit: September 24, 2015, 09:08:06 pm by DarkRoku »
I would like a spanish/latin community...
Problems building for Android? Look here

DarkRoku12

  • Full Member
  • ***
  • Posts: 203
  • Lua coder.
    • View Profile
    • Email
Re: SFML 2.0 and Box2d PRoblem
« Reply #8 on: September 24, 2015, 09:51:12 pm »
I made an example that works perfect



#include <iostream>
#include <SFML\Graphics.hpp>
#include <Box2D\Box2D.h>
#include <vector>

using namespace sf ;
using namespace std ;

#define TIMESTEP 1.0f/60.0f    
#define VELITER 10            
#define POSITER 10              



int main( int argc, char* argv[] )
{

        RenderWindow window( VideoMode( 800 , 600 ) , "myWindow" ) ;
                                 //window.setFramerateLimit( 1000 ) ;

    b2World world(b2Vec2(0.0f, 10.0f));

    //Definir Suelo Box2D
    b2BodyDef sueloBodyDef;
    sueloBodyDef.position.Set( 400 * 0.1 , 500 * 0.1 );
    b2Body* sueloBody = world.CreateBody(&sueloBodyDef);
    b2PolygonShape sueloBox;
    sueloBox.SetAsBox( 200 * 0.1 , 100 * 0.1 );
    sueloBody->CreateFixture(&sueloBox, 0.0f);
    // Crear ventana
    window.setFramerateLimit(60); //Hacer que los tiempos de refresco casen con los tiempos de Box2D

    sf::Vector2f m_Size;
    b2Body *m_pBody;
    b2PolygonShape polyShape;
    b2FixtureDef fixtureDef;
    b2BodyDef bodyDef;

        m_Size = sf::Vector2f(50.0f, 50.0f);
   
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set( 400 * 0.1 , 50.0f * 0.1 );
    m_pBody = world.CreateBody(&bodyDef);

    polyShape.SetAsBox( (50.0f/2) * 0.1 , (50.0f/2) * 0.1 ) ;

    fixtureDef.shape = &polyShape;
    fixtureDef.friction = 0.2f;
    fixtureDef.restitution = 0.3f;
    fixtureDef.density = 0.7f;

    m_pBody->CreateFixture(&fixtureDef);

    sf::RectangleShape rectSuelo( sf::Vector2f( 400 , 200 ) );
    rectSuelo.setOrigin( 400/2 , 200/2 );
    rectSuelo.setPosition( 400 , 500 ) ;
    rectSuelo.setFillColor(sf::Color::Red);

    sf::RectangleShape rect( sf::Vector2f( 50 , 50 ) );
    rect.setOrigin( 50/2 , 50/2 );
    rect.setPosition( 50 , 50 ) ;
    rect.setFillColor(sf::Color::Blue);

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

        }

                world.Step(TIMESTEP, VELITER, POSITER) ;

        window.clear() ;
                b2Vec2 pos = m_pBody->GetPosition() ;
                rect.setPosition( pos.x * 10 , pos.y * 10 ) ;
                window.draw(rectSuelo); //Dibujamos el elemento en el buffer
                window.draw(rect);
        window.display() ;
    }

        return 0 ;
}



 
I would like a spanish/latin community...
Problems building for Android? Look here

Hapax

  • Hero Member
  • *****
  • Posts: 3360
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: SFML 2.0 and Box2d PRoblem
« Reply #9 on: September 25, 2015, 12:31:53 am »
In rotation i use this #defines

#define TO_RAD 0.0174532925199432957f 
#define TO_DEGREES 57.295779513082320876f
Why do you prefer #define over const float?
I don't think floats have enough precision to store these values  ;D
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

GraphicsWhale

  • Full Member
  • ***
  • Posts: 131
    • View Profile
Re: SFML 2.0 and Box2d PRoblem
« Reply #10 on: September 25, 2015, 01:11:44 am »
Please just stick to English. It's difficult to read a thread when half of it is in Spanish.

I don't think floats have enough precision to store these values  ;D

Probably not a bad idea, though. The extra numbers are just trimmed off so it can fit, and if you ever want a double-precision version of the literal, you can just remove the f-prefix and the additional digits are there.

zsbzsb

  • Hero Member
  • *****
  • Posts: 1409
  • Active Maintainer of CSFML/SFML.NET
    • View Profile
    • My little corner...
    • Email
Re: SFML 2.0 and Box2d PRoblem
« Reply #11 on: September 25, 2015, 12:47:42 pm »
For reference as to what is wrong with the original code...

while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {....}
 
        window.clear(sf::Color::Black);
 
        world.Step(TIMESTEP, VELITER, POSITER);

        // Here is the problem
        // you recreate your character variable EVERY SINGLE FRAME
        // which creates a new fixture in the Box2d world at the default location...
        // so of course you never see the fixture moving in the world because you creating
        // a new one and then never running the physics on it
        Personaje personaje(world);
        personaje.run(window);

     
        window.display();
    }
Motion / MotionNET - Complete video / audio playback for SFML / SFML.NET

NetEXT - An SFML.NET Extension Library based on Thor

 

anything