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

Author Topic: SFML and Box2d  (Read 1778 times)

0 Members and 1 Guest are viewing this topic.

nerminsh

  • Newbie
  • *
  • Posts: 2
    • View Profile
SFML and Box2d
« on: November 20, 2020, 06:12:19 pm »
Hello,
so I'm trying to use SFML with box2d .. I created a GameObject class
class GameObject
{
public:
        Drawable* drawable;
        Shape* shape;
        b2Body* body;
        void setColor(Color color);
        void update();
        virtual void draw(RenderWindow* window) = 0;
};

and a box class
class Box: public GameObject
{
public:
        RectangleShape rectangle;
        Box(b2World* world, b2Vec2 position, b2Vec2 size, b2BodyType type, float density = 1, float friction = 0, uint16 category = 1, uint16 mask= 0xFFFF);
        void draw(RenderWindow* window)override;
};

I have a
vector<GameObject*> objects;
and every frame I update and draw the boxes

now the problem is this
if (Keyboard::isKeyPressed(Keyboard::Space))
{
         objects.push_back(&Box(&world, b2Vec2(0.0f, 4.0f), b2Vec2(4.0f, 4.0f), b2BodyType::b2_dynamicBody, 1, 0, 2));
}

when I try to draw after I've pressed space the app crashes

here is the draw function
void Box::draw(RenderWindow* window)
{
    window->draw(rectangle);
}
 

any Idea what might be the problem here

grapes

  • Newbie
  • *
  • Posts: 5
    • View Profile
    • Email
Re: SFML and Box2d
« Reply #1 on: November 21, 2020, 11:46:57 pm »
Not sure if you've fixed this yet but here's a solution:

When you do "&Box()" you are returning a pointer to a stack-allocated object of type Box. This stack-allocated object gets destroyed when the scope ends. So basically, the Box() instance you create in the if statement will no longer exist by the end of the if block.

What you should do is use the "new" keyword as that will create the Box() instance on the heap and return a pointer to it. This will only be destroyed when you tell it to.

Your program crashes because your Box() instance gets destroyed pretty much straight away. The pointer that you add to the vector, now points to the destroyed object. So, by the time you access the object the pointer is pointing to in your drawing loop, it has been destroyed. This makes your program crash.

When creating objects using "new", you must make sure you call "delete" to delete your Box() instance as to prevent memory leaks and such. I recommend googling about c++ pointers and such to learn more about it.

nerminsh

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: SFML and Box2d
« Reply #2 on: November 22, 2020, 07:48:02 am »
Thank You .. that was really helpful.

 

anything