1
\$\begingroup\$

What is better practice when a body goes out of screen, to destroy the body or just setActive(false)?

I guess in terms of memory it is better to destroy it and free the memory, but is destroying bodies expensive?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ How many bodies do you have? How frequently do you need to activate/create/deavtivate/delete them? Have you tried and profiled it? \$\endgroup\$
    – Vaillancourt
    Commented Jul 24, 2019 at 16:02
  • \$\begingroup\$ This is more of a background question since I'm new to Box2d. I'm thinking about the case of collectable items or falling platforms that go out of screen. \$\endgroup\$
    – xmac
    Commented Jul 24, 2019 at 16:13

2 Answers 2

0
\$\begingroup\$

There is no one answer that is correct. In certain cases you'd use Destroy, in others you'd use setActive. Which one to use depends on the situation.

For objects that are meant to go out the screen and never come back, definitely use Destroy. No question about it.

For objects that are outside of the screen, but could come in the screen again, you could use setActive(false) to disable that object, and enable it later.

I'm not familiar with libgx, so I can't speak about performance, but most tools/engines I've used out there handle properly what happens when an object exits the screen, so it doesn't have to be rendered and waste resources.

Also for your worry about the Destroy function, for 99% of the situations, you won't notice any performance hit using it. In most (if not all) tools, its designed in such a way that it destroyed all the easy stuff of an object, and queues up the difficult part to be handled when resources are available.

My advice would be, use what makes sense, and don't worry about performance, until it becomes a problem. If an object is meant to be destroyed (as in, not used anymore) then use Destroy otherwise setActive.

\$\endgroup\$
0
\$\begingroup\$

It is better to set active to false if the object is likely to be activated again. This saves recreating the object which is a bit more expensive.

If memory is an issue you could try using something like pooling to help with destroying bodies and keeping the cost down.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .