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

Author Topic: SFML Box2D another example  (Read 28459 times)

0 Members and 2 Guests are viewing this topic.

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« on: February 21, 2012, 08:10:20 pm »
I've been working with SFML for just a little bit now, and recently hopped on to Box2D for some simple development work.
It's been a great run, but so far one of my greatest problems has been finding updated sourced code for both.
I thought I would post this little example I made.

I found a decent example on the Box2D forums ;) but it was outdated,
so I updated it, and added some more functionality. It's very simple, and I hope it helps someone!

here is the link for the original code http://box2d.org/forum/viewtopic.php?f=3&t=8102&p=34828&hilit=sfml#p34828
thanks irresistable force!

box.h
Code: [Select]

//box.h
#ifndef BOX_H_
#define BOX_H_
#include <Box2D/Box2D.h>
#include <SFML/Graphics.hpp>

//i added this too, just for fun/show BHN
sf::Color randColor();

class CBox
{
private:
   b2Body * m_body;
   b2BodyDef m_bodyDef;
   b2PolygonShape m_bodyShape;
   b2FixtureDef m_bodyFix;
   sf::RectangleShape m_shape; //SFML shape
   static int n;
public:
   CBox(b2World & world);
   CBox();
   void SetWorld(b2World & world);
   b2Body* GetBody(); // Get Box2d body
   sf::Shape & GetShape();
   void update(); // Get SFML shape
   void ResetPosition(b2World & world); //this one is me too BHN resets shapes
   void jump(float angle);
   void setN(int newN) {n = newN;}  //reset n
   int getN() {return n;}
   ~CBox();
};



#endif


box.cpp
Code: [Select]

//box.cpp file
#include "box.h"
const int PPM = 30;

int CBox::n = 0;

CBox::CBox(b2World & world) {
m_shape = sf::RectangleShape(sf::Vector2f(20,20));//(0,0,50,50,sf::Color(255,255,255));
m_shape.SetOrigin(10,10);
m_shape.SetFillColor(sf::Color(255, 0, 255, 255));
    m_bodyDef.position.Set(300.0f/PPM,-300.0f/PPM-n*5/PPM);
    m_bodyDef.type = b2_dynamicBody;
    m_bodyShape.SetAsBox(10.0f/PPM,10.0f/PPM);
    m_bodyFix.shape = &m_bodyShape;
    m_bodyFix.density = 0.3f;
    m_bodyFix.friction = 0.5f;
    m_body = world.CreateBody(&m_bodyDef);
    m_body->CreateFixture(&m_bodyFix);
}

void CBox::SetWorld(b2World & world) {
    m_body = world.CreateBody(&m_bodyDef);
    m_body->CreateFixture(&m_bodyFix);
}

CBox::CBox() {
m_shape = sf::RectangleShape(sf::Vector2f(10.f,10.f));//(0,0,10,10,sf::Color(255,255,255));
    m_shape.SetOrigin(5,5);
m_shape.SetFillColor(randColor());
//cout << 300/PPM << " : " << -300/PPM-n*5/PPM << endl;
    m_bodyDef.position.Set(300.0f/PPM,-300.0f/PPM-n*5/PPM);
    n++;
    m_bodyDef.type = b2_dynamicBody;
    m_bodyShape.SetAsBox(5.0f/PPM,5.0f/PPM);
    m_bodyFix.shape = &m_bodyShape;
    m_bodyFix.density = 0.1f;
    m_bodyFix.friction = 0.1f;
}

b2Body* CBox::GetBody() {
    return m_body;
}

sf::Shape & CBox::GetShape() {
    return m_shape;
}

void CBox::update() {
    m_shape.SetRotation( m_body->GetAngle() );
    m_shape.SetPosition( m_body->GetPosition().x*PPM, m_body->GetPosition().y*PPM);
}

void CBox::ResetPosition(b2World & world) {
//destroy stuff (memory management, otherwise they build up)
m_body->DestroyFixture(m_body->GetFixtureList());
world.DestroyBody(m_body);
n++;
//m_shape.SetOrigin(5,5);
m_bodyDef.position.Set(300.0f/PPM,-300.0f/PPM-n*5/PPM);
m_bodyDef.angularVelocity = 0;
//m_bodyDef.angle = 270;
m_bodyDef.linearVelocity.Set(0, 60);
//reset fixture and body
SetWorld(world);
//reset shape
update();
}

void CBox::jump(float angle) {
m_body->SetAngularVelocity(angle);
}

CBox::~CBox()
{
}


sf::Color randColor() {
int color = rand() % 10;
switch (color) {
case 1:
return sf::Color::Blue;
break;
case 2:
return sf::Color::Red;
break;
case 3:
return sf::Color::Yellow;
break;
case 4:
return sf::Color::Cyan;
break;
case 5:
return sf::Color::Green;
break;
case 6:
return sf::Color::Magenta;
break;
case 7:
return sf::Color(120, 59, 25); //brownish
break;
case 8:
return sf::Color(25, 59, 25);
break;
case 9:
return sf::Color(25, 150, 125);
break;
default:
return sf::Color(220, 159, 125);
break;
}
}


main.cpp
Code: [Select]

/*

     This is some source code i found which i will use as a guided tutorial to play with.
props up to irresistable force on the bo2d forums
link to thread:
http://box2d.org/forum/viewtopic.php?f=3&t=8102&p=34828&hilit=sfml#p34828

Borys H.N. 2/17/12

*/
//main.cpp file
#include <iostream>
#include <Box2D/Box2D.h>
#include <SFML/Graphics.hpp>
#include <sstream>
#include <ctime>
#include "box.h"
#include <stdio.h>
#include <Windows.h>

const int PPM = 30;

using namespace std;

struct body
{
    b2BodyDef DEF;
    b2PolygonShape SHAPE;
    b2FixtureDef FIX;
    b2Body * BOD;
sf::RectangleShape RECT;
};

//modifies to float by BHN
string floatToStr(float number);
float framesPS(sf::Clock &);

int main() {
    sf::RenderWindow app(sf::VideoMode(800,600,32),"Application");

    b2Vec2 gravity(0.0f, 9.8f);
    b2World world(gravity);

    body ground;
    ground.DEF.position.Set(400.0f/PPM,600.0f/PPM);
ground.RECT = sf::RectangleShape(sf::Vector2f(8000,25));//100-50? is size?
ground.RECT.SetOrigin(4000,25);
ground.RECT.SetFillColor(sf::Color(200,75,20,255));
    ground.SHAPE.SetAsBox(4000.0f/PPM,25.0f/PPM);
    ground.BOD = world.CreateBody(&ground.DEF);
    ground.FIX.shape = &ground.SHAPE;
ground.FIX.density = .7f;
ground.FIX.friction = .9f;
    ground.BOD->CreateFixture(&ground.SHAPE,1.0f);

//text stuff to appear on the page
sf::Font myFont;
if (!myFont.LoadFromFile("../res/athena_u.TTF"))
return EXIT_FAILURE;
    sf::Text Text("FPS", myFont);
    Text.SetCharacterSize(20);
    Text.SetColor(sf::Color(0, 255, 255, 255));
    Text.SetPosition(25,25);
//added these guys BHN
sf::Text clearInstructions("Press [Space] to reset");
sf::Text jumpInstructions("Press [A] to make blocks jump");
clearInstructions.SetCharacterSize(18);
jumpInstructions.SetCharacterSize(18);
clearInstructions.SetColor(sf::Color(200, 55, 100, 255));
jumpInstructions.SetColor(sf::Color(200, 55, 100, 255));
clearInstructions.SetPosition(25, 50);
jumpInstructions.SetPosition(25, 70);

    float timeStep = 1 / 180.0f;
sf::Event Event = sf::Event();
    sf::Clock Clock;

    sf::Clock fpsClock;
    int frameNumber = 0;
    int lastFPSFrame = 0;
    string lastFPSDisplay;

    //int mouseXs = 0;
    //int mouseYs = 0;
    //int mouseXspeed = 0;
    //int mouseYspeed = 0;
    const int boxes = 400; //adding x boxes where?
    CBox good[boxes];
int i = 0;
    for(i; i < boxes; i++) {
good[i].SetWorld(world);
}
//these next two are all me. redefining ground properties for walls BHN
body leftWall;
    leftWall.DEF.position.Set(0.0f/PPM,-300/PPM);
leftWall.RECT = sf::RectangleShape(sf::Vector2f(25,8000));//100-50? is size?
leftWall.RECT.SetOrigin(0,4000);
leftWall.RECT.SetFillColor(sf::Color(200,75,200,255));
    leftWall.SHAPE.SetAsBox(25.0f/PPM,4000.0f/PPM);
    leftWall.BOD = world.CreateBody(&leftWall.DEF);
    leftWall.FIX.shape = &leftWall.SHAPE;
leftWall.FIX.density = .7f;
leftWall.FIX.friction = .9f;
    leftWall.BOD->CreateFixture(&leftWall.SHAPE,1.0f);

body rightWall;
    rightWall.DEF.position.Set(800.0f/PPM,-300/PPM);
rightWall.RECT = sf::RectangleShape(sf::Vector2f(25,8000));//100-50? is size?
rightWall.RECT.SetOrigin(25,4000);
rightWall.RECT.SetFillColor(sf::Color(100,205,20,255));
    rightWall.SHAPE.SetAsBox(25.0f/PPM,4000.0f/PPM);
    rightWall.BOD = world.CreateBody(&rightWall.DEF);
    rightWall.FIX.shape = &rightWall.SHAPE;
rightWall.FIX.density = .7f;
rightWall.FIX.friction = .9f;
    rightWall.BOD->CreateFixture(&rightWall.SHAPE,1.0f);

while(app.IsOpen())
    {
        world.Step(timeStep,8,3);
        //mouseXs = app.GetInput().GetMouseX();
        //mouseYs = app.GetInput().GetMouseY();
char buff[32];
sprintf_s(buff, "%f", framesPS(Clock));
Text.SetString("FPS: " + sf::String(buff));

        frameNumber++;
if (fpsClock.GetElapsedTime().AsMilliseconds() > 1000) {
            char buf[64];
            sprintf_s(buf, "FPS: %d\n", frameNumber - lastFPSFrame);
            lastFPSDisplay = string(buf);
            lastFPSFrame = frameNumber;
fpsClock.Restart();
            fflush(stdout);
        }

        sf::Event events;
        while (app.PollEvent(events)) {
switch (events.Type) {
case sf::Event::Closed:
app.Close();
break;
case sf::Event::KeyPressed:
if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Space)) {
app.Clear();
app.Display();
good->setN(0);
for(int i = 0; i < boxes; i++) {
good[i].ResetPosition(world);
}
}/* draw other squares
else if (sf::Keyboard::IsKeyPressed(sf::Keyboard::G)) {
app.Clear();
app.Display();
good->setN(0);
for(int i = 0; i < boxes; i++) {
good[i] = CBox(world);
}
} */else if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Escape))
app.Close();
else if (sf::Keyboard::IsKeyPressed(sf::Keyboard::A)) {
for(int i = 0; i < boxes; i++) {
good[i].jump(90);
}
}

break;
}
}

        for(int i = 0; i < boxes; i++) {
            good[i].update();
        }

       ground.RECT.SetPosition(ground.BOD->GetPosition().x*PPM,ground.BOD->GetPosition().y*PPM);
  //offset by 25? why?
  leftWall.RECT.SetPosition(leftWall.BOD->GetPosition().x*PPM, leftWall.BOD->GetPosition().y*PPM);
  rightWall.RECT.SetPosition(rightWall.BOD->GetPosition().x*PPM, rightWall.BOD->GetPosition().y*PPM);
        //mouseXspeed = app.GetInput().GetMouseX() - mouseXs;
        //mouseYspeed = app.GetInput().GetMouseY() - mouseYs;

        app.Clear();
        app.Draw(ground.RECT);
app.Draw(leftWall.RECT);
app.Draw(rightWall.RECT);
app.Draw(Text);
app.Draw(clearInstructions);
app.Draw(jumpInstructions);
        for(int i = 0; i < boxes; i++)
            app.Draw(good[i].GetShape());
       

        /*glMatrixMode(GL_PROJECTION);
         glLoadIdentity();
         glOrtho(-50, 50, -50, 50, -1, 1);
         glMatrixMode(GL_MODELVIEW);
         glLoadIdentity();
         world.DrawDebugData();*/

        app.Display();
    }

    return 0;
}

float framesPS(sf::Clock & clock)
{
    bool sec = false;
    int count = 0;
    count++;
if(clock.GetElapsedTime().AsMilliseconds() >= 1000)
    {
        sec = true;
        clock.Restart();
        count = 0;
    }
float t = (float)clock.GetElapsedTime().AsMilliseconds();
    float ret = 0;
    if ( t ==  0 ) return 0;
else {ret = count / (float)clock.GetElapsedTime().AsMilliseconds(); }
    if ( sec){
char buf[64];
        sprintf_s(buf, "%f\n", ret);
        fflush(stdout);}
    return ret;
}



eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
SFML Box2D another example
« Reply #1 on: February 21, 2012, 08:15:38 pm »
Wow this looks promissing!  :wink:

I've been trying to get them to work with each other, but the strange and a bit messy API of Box2D didn't help much...

I'll defently check it out in depth once I find time.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #2 on: February 21, 2012, 08:23:13 pm »
haha yea, Box2D takes a little bit of your own organization, but once you start getting your own library of code built up it gets easier. Let me know what you think of the code when you get the chance!

G.

  • Hero Member
  • *****
  • Posts: 1593
    • View Profile
SFML Box2D another example
« Reply #3 on: February 21, 2012, 10:54:01 pm »
Do your boxes rotate correctly ?
I looked at your picture and felt that boxes on the ground shouldn't have this angle, so I quickly checked your code and found out that you're using the same angle in your CBox::update() function for both sf::Shape and b2Body. But last time I checked SFML was using degree for angle whereas box2D was using radians.

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #4 on: February 21, 2012, 11:10:06 pm »
haha no they do not. like i said it's really simple.
I just needed some quick sample code working to integrate and sync Box2D objects with SFML objects,
I wasn't too concerned with the actual physics.  
Feel free to add some more functionality!

Also looking back at the code, it's very rushed,
I didn't completely clean it up, so it's a bit messy, my apologies!

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #5 on: February 21, 2012, 11:21:44 pm »
on the neatness note, if you were looking to start breaking apart the code in main() you could introduce a function...

Code: [Select]

...

//body is a struct definition in main.cpp
void createBorder(body &aBody, float xpos, float ypos, float xorigin, float yorigin, sf::Color fill) {
aBody.DEF.position.Set(xpos/RATIO, ypos/RATIO);
   aBody.RECT = sf::RectangleShape(sf::Vector2f(xorigin*2,yorigin));
aBody.RECT.SetOrigin(xorigin, yorigin);
aBody.RECT.SetFillColor(fill);
   aBody.SHAPE.SetAsBox(xorigin/RATIO,yorigin/RATIO);
   aBody.FIX.shape = &body.SHAPE;
aBody.FIX.density = .7f;
aBody.FIX.friction = .9f;
aBody.BOD = world->CreateBody(&body.DEF);
   aBody.BOD->CreateFixture(&body.SHAPE,1.0f);
}

...

int main() {
...
       body floorAndWalls[3];
       floorAndWalls[0] = createBorder(...);  //floor properties
       floorAndWalls[1] = createBorder(...);  //leftwall properties
       floorAndWalls[2] = createBorder(...); //rightwall properties
...
}



neater already (:

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #6 on: February 22, 2012, 05:15:12 am »
I'm building a little level with a character i can make move, and hop around,
and i implemented this function, and I realize I have a misunderstanding as
too how to offset the fixtures to align perfectly with the rest of the shape.

i.e. i can have the character walk off a shape and "float", or "hit" a wall
i can hard code the fixtures with offsets, but i don't have the function working correctly.

any one have an idea?

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #7 on: February 22, 2012, 07:27:47 am »
I don't mean to keep talking to myself :roll: but I solved my own problem.
I split the function I provided into two. one for horizontal wall structs, and
one for vertical wall structs. The Box2D, and SFML objects line up pefectly on all sides.

Code: [Select]

//to create floor and ceiling
void createHBorder(aBody &body, float xpos, float ypos, float xorigin, //this is a generaic function i will use to create the walls and floor;
               float yorigin, sf::Color fill) {
body.DEF.position.Set(xpos/RATIO, ypos/RATIO);
body.DEF.type = b2_staticBody;
body.RECT = sf::RectangleShape(sf::Vector2f(xorigin*2,yorigin));
body.RECT.SetOrigin(xorigin, yorigin/2);
body.RECT.SetFillColor(fill);
    body.SHAPE.SetAsBox(xorigin/RATIO, (yorigin/2)/RATIO);
    body.FIX.shape = &body.SHAPE;
body.FIX.density = .7f;
body.FIX.friction = .9f;
body.BOD = world->CreateBody(&body.DEF);
    body.BOD->CreateFixture(&body.SHAPE,1.0f);
//set position
body.RECT.SetPosition(body.BOD->GetPosition().x*RATIO, body.BOD->GetPosition().y*RATIO);
}  

//to create walls                  //300 800
void createVBorder(aBody &body, float xpos, float ypos, float xorigin, //this is a generaic function i will use to create the walls and floor;
               float yorigin, sf::Color fill) {
body.DEF.position.Set(xpos/RATIO, ypos/RATIO);
body.DEF.type = b2_staticBody;
body.RECT = sf::RectangleShape(sf::Vector2f(xorigin,yorigin*2));
body.RECT.SetOrigin(xorigin/2, yorigin);
body.RECT.SetFillColor(fill);
    body.SHAPE.SetAsBox((xorigin/2)/RATIO,yorigin/RATIO);
    body.FIX.shape = &body.SHAPE;
body.FIX.density = .7f;
body.FIX.friction = .9f;
body.BOD = world->CreateBody(&body.DEF);
    body.BOD->CreateFixture(&body.SHAPE,1.0f);
//set position
body.RECT.SetPosition(body.BOD->GetPosition().x*RATIO, body.BOD->GetPosition().y*RATIO);
}


I'd love to know if this works for anyone else tho. Maybe someone can find a special case I haven't seen.

Bigz

  • Full Member
  • ***
  • Posts: 154
    • View Profile
    • Bigz.fr
SFML Box2D another example
« Reply #8 on: February 22, 2012, 10:42:12 am »
Hm, maybe I can help you. I often work with Box2D and SFML and those last days I made a little application which parse a SVG file (vector draw) and create a Box2D / SFML scene.

If you want see my code to better understand how to render your box2D seen, feel free to read those sources : http://code.google.com/p/svg-to-box2d/source/browse/#svn%2Ftrunk

Unfortunatly, my code isn't clear yet and not entirely commented, but still, that can help :P

Edit : This project use the SFML 2.0 BEFORE the huge change of the graphic API, so it's not a good idea to use this code, but it should be easy to adapt it.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
SFML Box2D another example
« Reply #9 on: February 22, 2012, 08:04:12 pm »
I've looked at the code and unfortunatly it's not very usable...  :oops:
The code is pretty messy and would take a lot of work to clean up.
Also after changing from an array to an std::vector I couldn't run it anymore and just got some "pure virtual function called" error from within Box2D where I then stopped looking into it.

If someone wants to proceed here are three links to the files:
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #10 on: February 23, 2012, 12:04:41 am »
if you get a pure virtual function call error it means you called a function that you haven't defined in your class which extends the class of the function your calling.

hope that helps

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #11 on: February 23, 2012, 02:16:05 am »
Quote from: "Bigz"
Hm, maybe I can help you. I often work with Box2D and SFML and those last days I made a little application which parse a SVG file (vector draw) and create a Box2D / SFML scene.

If you want see my code to better understand how to render your box2D seen, feel free to read those sources : http://code.google.com/p/svg-to-box2d/source/browse/#svn%2Ftrunk

Unfortunatly, my code isn't clear yet and not entirely commented, but still, that can help :P

Edit : This project use the SFML 2.0 BEFORE the huge change of the graphic API, so it's not a good idea to use this code, but it should be easy to adapt it.


not bad! I was just talking with someone about scene management. I have a lot to learn. I will be taking a look at that code.

here's another project i started, this one is much neater, with better code.
git hub repo https://github.com/BorysHN/SFML-Box2D-Simple-Level still not perfectly clean. the background image causes a
crash when exiting the application.


eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
SFML Box2D another example
« Reply #12 on: February 23, 2012, 08:58:44 am »
Yeah I know what the error means, the problem is just finding were the given code goes wild or what's the problem with using vectors over an array.

I took a look at your little game from github. I still have a bit a diffrent definition on clean code but hey you go something done, I didn't. ^^

Anyway there is some problem in the movement. If an arrow key is pressed you do not reposition the player. Also if you would reposition and a arrow key is pressed it would only move left or right since you override the y-velocity...
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

tbny

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • http://www.soundcloud.com/borysn
SFML Box2D another example
« Reply #13 on: February 23, 2012, 05:52:39 pm »
Quote from: "eXpl0it3r"
Yeah I know what the error means, the problem is just finding were the given code goes wild or what's the problem with using vectors over an array.

I took a look at your little game from github. I still have a bit a diffrent definition on clean code but hey you go something done, I didn't. ^^

Anyway there is some problem in the movement. If an arrow key is pressed you do not reposition the player. Also if you would reposition and a arrow key is pressed it would only move left or right since you override the y-velocity...

haha my movement is very hacked! it was quick. it took me a little bit to do the rest, like getting him drawn correctly, but
 I do see what you're sayin and ill have that fixed. As well as adding a simple item and enemy class.
probably no real AI, just a simple projectile. aimed at the player.

I do plan on continuing to expand my code in efficiency and practicality with little projects like these, so I appreciate the feedback!

morando

  • Newbie
  • *
  • Posts: 16
    • View Profile
SFML Box2D another example
« Reply #14 on: March 05, 2012, 12:45:40 am »
Hi, sorry for intrusion on this topic.
I have some problem with Box2D and SMFL, especialy circle shapes, i made a minimalistic code that shows problem:
VS2010
Box2D 2.21
SMFL 2.0

Code: [Select]

#include <iostream>

// SMFL
#include <SFML/Graphics.hpp>
#pragma comment(lib, "sfml-graphics-d.lib")
#pragma comment(lib, "sfml-window-d.lib")
#pragma comment(lib, "sfml-system-d.lib")

// Box2D
#include <Box2D/Box2D.h>
#pragma comment(lib, "Box2D.lib")

#define B2_PIXEL_RATIO 30.0f

int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
sf::Vector2f winSize = window.GetDefaultView().GetSize();

sf::Vector2f shapePosition(winSize.x * 0.5f, winSize.y * 0.5f);

// Rect body
float radius = 20.0f;
sf::CircleShape  rcShape(radius);
rcShape.SetPosition(shapePosition);
rcShape.SetFillColor(sf::Color(255,255,0,255));

b2World  phWorld(b2Vec2(0, 0));

b2BodyDef shapeBodyDef;
shapeBodyDef.type     = b2_dynamicBody;
shapeBodyDef.position = b2Vec2(shapePosition.x / B2_PIXEL_RATIO, shapePosition.y / B2_PIXEL_RATIO);
b2Body* shapeBody     = phWorld.CreateBody(&shapeBodyDef);

b2CircleShape circleShape;
circleShape.m_radius = radius / B2_PIXEL_RATIO;

b2FixtureDef rcShapeFixDef;
rcShapeFixDef.shape       = &circleShape;
rcShapeFixDef.density     = 10.0f;
rcShapeFixDef.friction    = 0.4f;
rcShapeFixDef.restitution = 1.0f;
shapeBody->CreateFixture(&rcShapeFixDef);

// Surround screen with static edges
b2FixtureDef groundBoxDef;
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);
b2Body* groundBody = phWorld.CreateBody(&groundBodyDef);

b2Vec2 vs[5];
vs[0].Set(winSize.x / B2_PIXEL_RATIO, 0.0f);
vs[1].Set(winSize.x / B2_PIXEL_RATIO, winSize.y / B2_PIXEL_RATIO);
vs[2].Set(0.0f, winSize.y / B2_PIXEL_RATIO);
vs[3].Set(0.0f, 0.0f);
vs[4].Set(winSize.x / B2_PIXEL_RATIO, 0.0f);
b2ChainShape wallShape;
wallShape.CreateChain(vs, 5);
groundBoxDef.shape = &wallShape;
groundBody->CreateFixture(&groundBoxDef);

float scale = 5.0f;
shapeBody->SetLinearVelocity(b2Vec2(scale, scale));

while(window.IsOpen())
{
sf::Event event;
while (window.PollEvent(event))
{
if (event.Type == sf::Event::Closed)
window.Close();
}

float timeStep = 1.0f / 6000.0f;
phWorld.Step(timeStep, 10, 10);

float x = shapeBody->GetPosition().x * B2_PIXEL_RATIO;
float y = shapeBody->GetPosition().y * B2_PIXEL_RATIO;
rcShape.SetPosition(x, y);

window.Clear();
window.Draw(rcShape);
window.Display();
}
return EXIT_SUCCESS;
}



When i run this circle has some offset and penetrates bottom & right part of the screen and also for left & top can't reach all the way.
Sorry for my english, can't explain any better, and i am really frustrated as i can't find out whats wrong.
If you find time, please help.

 

anything