0

When creating Box2D sidescroller game, is it performance friendly to scroll through every object and move it (for example by x axis) as it does in the following code snap:

for(Body b: bodies) {
    b.setTransform(-1, b.getPosition().y, b.getAngle());
}

I was also wondering about the rendering, if I render every texture on every body, I would be rendering the whole level at once and it would cost a lot of my precious FPS.

Vilda
  • 1,675
  • 1
  • 20
  • 50
  • But then when do I know that the new body has to appear on the screen? – Vilda May 15 '14 at 15:31
  • I dont know about box2d performance ,but for god shake don't use for each loop with an ArrayList ,you will drive the GC crazy, foreach is creating an iterator everytime you call it.Object creation inside the game loop is the main reason for poor performance in many games in the play store. – SteveL May 15 '14 at 15:38
  • What else should I use then? – Vilda May 15 '14 at 16:36
  • The classic for(int i=0;i – SteveL May 15 '14 at 16:39
  • And this doesn't create inner object which has to be managed by GC? – Vilda May 15 '14 at 16:40
  • Yes it doesn't create any object,if you want to see for your self the evil of foreach ,just use the DDMS tool of eclipse and check for allocations,or just check the logcat and you will see messages like 'GC_CONCURRENT freed 704K, 15% free 12439K/14471K, paused 13ms+13ms, total 69ms' – SteveL May 15 '14 at 16:41

1 Answers1

3

In contrast to the comments saying that this is a good way to do it, I don't think so.

It is not intuitive to move every entity in your world. When you run around through a forest in real life, the trees also don't move around you, but only you move.

Use an OrthographicCamera and change its position. When rendering via a SpriteBatch, draw all bodies exactly on the position where they are (probably with some METER_TO_PIXEL scaling factor) and use spriteBatch.setProjectionMatrix(camera.combined) on your SpriteBatch. This way only the visible bodies will be drawn automatically, since the camera transformation will get rid of all non-visible bodies.

And another hint: Try to avoid Body.setTransform(). Instead try setting linear velocity or apply forces/torque on the bodies. Using setTransform causes non-physical behaviour since it's basically like teleporting and might lead to weird effects and in my case sometimes even bugs.

noone
  • 19,520
  • 5
  • 61
  • 76
  • I didn't knew that using Camera will get rid of non-visible bodies. Do you happen to know, how set the scene so only visible bodies will by physicaly awake? – Vilda May 16 '14 at 04:13
  • The camera won't get rid of them, but they won't be drawn of course. If you want to disable non-visible bodies, you need to perform an AABB query on the `World`, with your camera's viewport as the AABB and then disable all bodies that are not in this query. – noone May 16 '14 at 12:56