JBox2D collisions not bouncing - java

I have an Android application using JBox2D for physics simulation. The only dynamic object is a 0.07m radius circle, as well as several static circles and rectangles in a total game area of about 20m by 20m. I'm also using a few custom forces through the ApplyForce method.
Whenever any bodies collide, they do collide correctly however they don't bounce; everything just thuds together. All bodies have their densities, frictions and restitutions set (some objects have a restitution greater than 1).
Does anyone have any ideas why these collisions aren't working? I think it might be because the bodies aren't moving fast enough for JBox2D to count as proper collisions (there is a cutoff in Box2D).
Thanks!

setting Settings.velocityThreshold = 0.0001f; (or very small) solved it for me.

I found a partial solution to this - Box2D (at least JBox2D) ignores restitution if the velocity is below a certain threshold - by scaling all my objects up by a factor of 10, the threshold becomes relatively lower, and objects bounce.

Related

2D physics game performance problems (libgdx box2d in android)

I am making a 2D car game like earn to die 2. I ve almost completed it. Only problem is the physics engine performance. I am using box2d and there are 10 meters length edge shapes totally building a 100 km terrain. 1 car and usually 30-40 boxes. Number of active dynamic bodies is around 60-100, max 120. Game fluently working in desktop but in android fps drops below 30 when actives bodies are more than 60. There are collisions between car and boxes and boxes each other and both box and car to ground.
I am using libgdx framework 1.9.4 as version, java is 1.7, coding with eclipse neon, windows 7.
this is how I am counting active bodies in world
int num=0;
Array<Body> bodies=new Array<>();
world.getBodies(bodies);
for(Body b:bodies){
if(b.isActive())num++;
}
active dynamic bodies are usually around 100
it is not a drawing issue with all terrain and underground meshes and car and boxes cost 6-7 mili seconds I measured them when box2d debug rendered is off and world step method call costs about 30 mili seconds when there are about 30 boxes while the car is crushing into them
I don't load all game objects (boxes for now) I splitted entire map into chunks map size is 100 km and chunk size is 50 meters when the car is in the next 50 meters ( in the chunk range) I load the boxes from a ready pool ( box2d world representations of the those objects are also pooled and when the boxes are in pool I deactivate their box2d body with setActive(false) and back to true while the chunk is loading)
I applied this chunk system for terrain too. I load all the terrain when the game is loading then deactivate them by setting with this method setActive(false) and when the car goes on trough the map if the chunk range includes car's x axis coordinate I activate the next chunk which contains the terrain static bodies having around 20 fixtures with size of 10 meters, makes the chunk size 200 meters at total.
the green lines are active terrain shapes as you see left and right after a distance are deactivated till the end of the map this part is from around 60 km of the map in middle of 100 km terrain map.
when vehicle moved little more new boxes will load there ahead and old ones will be pooled if they are 20 meters back from the car.
My questions are
1) is this fps (20 fps) normal and expected?(android 7 this is phone specifications http://www.androidpolice.com/2016/02/23/the-general-mobile-gm-5-plus-is-the-most-powerful-android-one-device-yet/)
2) can the 100 km terrain be problem if so how should I manage it?
->I tried activating/deactivating terrain bodies when they out of the screen rectangle.
->I tried hundreds of fixtures on a single body or every terrain piece is as separated body but best performance with I splited 100 km terrain into 200 meters chunks and each chunk is a body and consist of about 20 fixtures.
3) simulating 100 dynamic bodies with huge edge shape terrain is tottaly impossible ? ( but in the earn to die they did it)
4) should I write my own simple physics for only this kind of game (a simple specific one) ?
5) should I use bullet physics instead of box2d for 2D purposes ? is it possible? and will I face with performance problems ?
if you need any code pls comment, I will add.
are there any really fast physics engines I couldn't find on the net if there are do you suggest to change box2D ?
good to note:
I am simulating box2d with constant time step I tried 1/60 1/45 1/30 and 8-3 , 6-
2 as iteration steps.
I use high damping values like .9 for both linear and angular for all bodies.
I also would like to split those boxes into pieces actually I am doing it but without splitting hem when car crushed I am experiencing this fps drop so I disabled it for now.
Only joints are wheel joints and used for wheel of car no more joints in anywhere in map.
Sizes are realistic those boxes are 1.2 meters high.
for boxes and cars polygon shapes used for terrain edge shapes used (chain shape)
velocity threshold is 1 as default in world settings.
if there are any notes I forgot pls comment and I will share.
thank you.
Disclaimer: I can't answer all of your question, and below are just a guess from me.
A few years ago, I developed a game prototype and game library with Java + box2d + plain Opengl (LWJGL).
I think you are facing some issues that occurred to me.
However, with my low experience, I could be wrong.
If experts (readers) think that there are any mistake in my post, please comment below, I will fix it.
My guess
Java is slow / not quite suitable for game.
Disclaimer: There is a lot of argument about this.
I am not an expert enough to put a solid statement here, but I see a lot of my game-prototype run 3x-10x faster in C++ than Java. (with not-so-different algorithm)
Memory fragmentation
As you may already know, even you use pool, it is still very poor compared to C++.
You pool the boxes, but you can't pool everything, e.g. game logic data-structure, vector2D, plain array (new[] often), some horror algorithm in some libraries that you use.
Deactivated bodies still cost memory (intensify memory fragmentation indirectly).
You have a lot of static bodies / high complexity of static body.
You didn't mention how many static body you have, and what are them.
Are you using a high-amount-of-vertices shape for the terrain?
Popular physic engines like Box2D and Bullet are cool at convex shape, and expert at primitive shape, but tend to work poorly with concave shape (e.g. your terrian)
Your shapes are continuously colliding each other.
For example, a stack of 100 boxes cost a lot more computation than 100 boxes scattering around the scene.
Too large world
As far as I know, box2d divide a scene (world) into a grid. If your world is very large, but a lot of body cluster into the same cell of the grid, Box2D will work relatively worse.
It is not limited to Box2D.
Bullet and Ogre3D - in certain configuration - also suffer from this issue.
Answer (guess again)
1) is this fps (20 fps) normal and expected?
I don't know about moblie, but your code can still be optimized in some ways. (see below)
2) can the 100 km terrain be problem if so how should I manage it?
Unfocused chunk -> remove the body (not just deactivated it).
Yes, it is easier said than done, you may just deactivate near chunk, but remove (delete) all bodies in chunk that is far away (> 3 chunk-distance, may be).
If the deleted chunk can come back to the scene, you may have to find a way to save it somewhere. (e.g. save only position of body, size, weight)
3) simulating 100 dynamic bodies with huge edge shape terrain is tottaly impossible ? ( but in the earn to die they did it)
They did, or you just think they did?
In some aspect, programming is an art.
Thing you see can be very different from how they are actually implemented.
You bottleneck may be only the terrain - reduce its level-of-detail may also help.
4) should I write my own simple physics for only this kind of game (a simple specific one) ?
No, except you want to learn && have a lot of time && really love Math.
5) should I use bullet physics instead of box2d for 2D purposes ? is it possible? and will I face with performance problems ?
I think you will still face in some degree.
Constraint is expensive for both Box2D and Bullet.
Are you sure you really need constraint?
In some cases, it can be avoided with compound shape / modify design of the game a bit.
I think if you change to C++ and Bullet, you will gain about at least 3x performance, but I am not sure about it at all.

Java Path2D performance issue

I have a program that utilizes Path2D.Float to draw a vector object (a large fractal design). My code allows zooming and panning. I have an axis object that has methods to convert world coordinates (pairs of doubles) to display coordinates (pairs of floats) based on the current scaling settings (stored in the axis object).
Anyways, the vector graphic is large and detailed and contains many line segments in world coordinates. Each time the user zooms or pans, new Path2D objects are created and rendered to the screen.
Everything is perfectly smooth when zoomed out. The problem occurs when I zoom in to a certain depth. Apparently the Path2D lines get very long and this slows down their rendering (even though the vast majority is outside the viewing area!). It's not my conversion algorithms consuming resources. I profiled it and it's definitely the Java graphics drawing algorithm that's slowing down due to the size of the lines in comparison to the small clipping region.
I was hoping there was a way to get Java to deal with the clipping of large lines automatically. I do call setClip() from the graphics object before drawing. I don't see what's taking so much time. Is there something problematic/inefficient about the clipping algorithm when lines are long in comparison the clipping rectangle? I don't think I'm zooming so far that my conversion from world coordinates to display coordinates is causing overflow. I'll have to check for this. If that's the case I'll try using Path2D.double instead.
Anyways, any help appreciated. I'm sure I'll eventually figure this out but I hope someone that's encountered the same problem can give me a pointer so it doesn't take so long to figure out.
I've not used paths when zooming, but I have used them for drawing some very complex shapes with textures & gradients etc. Some issues I had were:
In my experience, I had to avoid creating new Path2D objects on a per frame basis because of performance issues, not just for their recreation execution, but because it caused a lot of garbage collection with generating & then dropping so many so quickly, which slowed things down. If your shape doesn't change, cache the generated path.
Avoid clipping with paths - where possible stick to rectangles - paths seem to give rough edges on curves and are more costly to use.
Even when clipping to smaller regions, simply asking to draw large regions could slow things down. Consider when the user zooms in to tessellate your shape, i.e. the shape is only as big as your viewport. Perhaps as you say maybe there is an issue with the clip function when dealing with large volume areas, so tessellation might help here.

Trying to achieve dynamic lighting in a tiled 2D isometric environment using Java2D

I am trying write some lighting code for a Java2D isometric game I am writing - I have found a few algorithms I want to try implementing - one of which I found here:
here
The problem is that this sort of algorithm would require some optimal pixel-shading effect that I haven't found a way of achieving via Java2D. Preferably some method via the graphics hardware but if that isn't possible - at least a method of achieving the same effect quickly in software.
If that isn't possible, could someone direct me to a more optimal algorithm with Java2D in mind? I have considered per-tile lighting - however I find the drawPolygon method isn't hardware accelerated and thus performs very slowly.
I want to try and avoid native dependencies or the requirement for elevated permissions in an applet.
Thanks
I did a lot of research since I posted this question - there are tons of alternatives and JavaFX does intend (on a later release) to include its own shader language for those interested. There is also a ofcourse LWJGL that will allow you to load your own shaders onto the GPU.
However, if you're stuck in Java2D (as I am) it is still possible to implement lighting in an isometric game it is just 'awkward' because you cannot perform the light shading on a per-pixel level.
How it Looks:
I have achieved a (highly unpolished - after some polishing I can assure you it will look great) effect for casting shadows, depth sorting the light map, and applying the lighting without experiencing a drop in frame-rate. Here is how it looks:
You'll see in this screen-shot a diffuse light (not shaded in but that step I'd say is relatively easy in contrast to the steps to get there) casting shadows - the areas behind the entities that obstructs the light's passage BUT also in the bounds of the light's maximum fall-out is shaded in as the ambient lighting but in reality this area is passed to the lights rendering routine to factor in the amount of obstruction that has occurred so that the light can apply a prettier gradient (or fading effect of some sort.)
The current implementation of the diffuse lighting is to just simply render obstructed regions the ambient colour and render non-obstructed regions the light's colour - obviously though you'd apply a fading effect as you got further from the light (that part of the implementation I haven't done yet - but as I said it is relatively easy.)
How I did it:
I don't guarantee this is the most optimal method, but for those interested:
Essentially, this effect is achieved by using a lot of Java shape operations - the rendering of the light map is accelerated by using a VolatileImage.
When the light map is being generated, the render routine does the following:
Creates an Area object that contains a Rectangle that covers the
entirety of the screen. This area will contain your ambient
lighting.
It then iterates through the lights asking them what their
light-casting Area would be if there were no obstructions in the way.
It takes this area object and searches the world for Actors\Tiles
that are contained within that area that the light would be cast in.
For every tile that it finds that obstructs view in the light's casting area, it will calculate the difference in the light source's position and the obstruction's
position (essentially creating a vector that points AT the
obstruction from the light source - this is the direction you want to cast your shadow) This pointing vector (in world
space) needs to be translated to screen space.
Once that has been done, a perpendicular to that vector is taken and
normalized. This essentially gives you a line you can travel up or
down on by multiplying it by any given length to travel the given direction in. This vector is
perpendicular to the direction you want to cast your shadow over.
Almost done, you consturct a polygon that consists of four points.
The first two points are at the the base of the screen coordinate of
your obstruction's center point. To get the first point, you want to
travel up your perpendicular vector (calculated in 5) a quantity of
half your tile's height [ this is a relatively accurate
approximation though I think this part of the algorithm is slightly
incorrect - but it has no noticable decay on the visual effect] -
then ofcourse add to that the obstructions origin. To get the
second, you do the same but instead travel down.
The remainder of the two points are calculated exactly the same way -
only these points need to be projected outward in the direction of
your shadow's projection vector calculated in 4. - You can choose any large amount to project it outwards by - just as long as it reaches at least outside of you light's casting area (so if you just want to do it stupidly multiply your shadow projection vector by a factor of 10 and you should be safe)
From this polygon you just constructed, construct an area, and then
invoke the "intersect" method with your light's area as the first
argument - this will assure that your shadows area doesn't reach
outside of the bounds of the area that your light casts over.
Subtract from your light's casting the shadow area you constructed
above. At this point you now have two areas - the area where the
light casts unobstructed, and the area the light casts over
obstructed - if your Actors have a visibility obstruction factor
that you used to determine that a particular actor was obstructing
view - you also have the grade at which it obstructs the view that
you can apply later when you are drawing in the light effect (this will allow you to chose between a darker\brighter shade depending on how much light is being obstructed
Subtract from your ambient light area you constructed in (1) both
the light area, and the obstructed light area so you don't apply
the ambient light to areas where the lighting effect will take over
and render into
Now you need to merge your light map with your depth-buffered world's render routine
Now that you've rendered you're light map and it is contained inside of a volatile image, you need to throw it into your world's render routine and depth-sorting algorithm. Since the back-buffer and the light map are both volatileimages, rendering the light map over the world is relatively optimal.
You need to construct a polygon that is essentially a strip that contains what a vertical strip of your world tiles would be rendered into (look at my screen shot, you'll see an array of thin diagonal lines seperating these strips. These strips are what I am referring). You can than render parts of this light map strip by strip (render it over the strip after you've rendered the last tile in that strip since - obviously - the light map has to be applied over the map). You can use the same image-map just use that strip as a clip for Graphics - you will need to translate that strip polygon down per render of a strip.
Anyway, like I said I don't guarantee this is the most optimal way - but so far it is working fine for me.
The light map is applied p

Collision Detection in libgdx

My question is mostly related to the theory behind it. I make a 2D game for a project and i detect collisions by using the .overlaps method in the Rectangle class and the collisions are handled beautifully. First of all , is that considered to be a continuous or discrete collision technique. As i'm reading the theory i say it is discrete ,however i'm reading in online articles that the major disadvantage of discrete is that it detects collision after it actually happened. So,my question is the following : is it actually discrete and if it is why i see no disadvantages?
Thanks
This is discreet because we only know if two bounding boxes collided after we check if the imaginary/invisible boxes intersected meaning they already overlapped. So by the time you take action (update) due to that collision, the objects are not in the collided position. Worse case, if they are not in relative speed, they can pass through. Think of the classic helicopter game where you dodge obstacles by going up and down. Say you put the velocity of the chopper on x really high, depending on your frame rate which depends on the hardware, you will see different positions of actual collision. For continuous, one object has to be aware of the physics properties of the other objects it may collide with to predict possible collision.
In reality, for 2d games like the helicopter game I mentioned, it really doesn't matter much. You can simulate the result of the collision by doing changes on an object's rotation, velocity, gravity and through some nice animations. If your game objects have abstract shapes, you should use something like box2d. There's a good Intersector class as well.
Also, you can experiment with different bounding box sizes (bounds) of an object rather than creating the bounding box of the object equal to its width and height.

Bodies overlapping in 2D Physics simulation (Java)

I made a program in Java where circles can bounce into each other and gravitate towards each other.
For the most part (few circles on the screen), there are no noticeable bugs. The problem starts to happen when there is a large amount of circles on screen. Sometimes, the circles will overlap if it gets too crowded. It's as if the weight of all the other circles are crushing the circles together, causing them to overlap. Of course, there program doesn't know anything about how much a circle weighs, so it's not really crushing. Most likely, the piece of logic that handles resolving collisions is not able to handle crowded situations.
Circles are stored in an array, and each circle goes through the array using a for loop, comparing itself to the other circles. If the distance between the center of this circle and the center of the other circle is less than the sum of their radii, then the circles are colliding. The velocities of both circles are updated using an equation for collisions.
I think the problem occurs because if a circle is surrounded, it might receive an updated velocity into the circle behind it, while the circle behind it also receives an updated velocity into the former circle. In other words, the two circles get told to move toward each other, even though they are already touching. Once they overlap this way, I don't know why they don't undo their overlap.
I've tried restoring touching scenario if they are overlapping by finding the distance they are overlapped, then moving them apart from each other; each moves half the overlap distance apart. This doesn't change the circle's velocity, only their position.
This still doesn't solve the problem. If the circle is surrounded, and it overlaps with one of it's neighboring circles, its position is changed so they aren't overlapping, but this new position may cause it to overlap with another circle. Same problem.
If there was no gravity pushing the circles together, they would eventually spread out and resolve their overlapping issues, but the gravity prevents this from happening.
Further information:
Gravity is not taken into account when calculating new velocities after a collision.
Sounds like your hunches about what is causing the problem are correct in both cases.
Unfortunately, there's no easy way to fix this issue - it pretty much means rewriting your whole collision detection & resolution code from scratch. You have to work out the exact timing of the first collision, update everything only that far, resolve the collision (do your velocity update) then work out the exact timing of the next collision, then repeat...
Writing a good physics engine is hard, there's a good reason that there are many textbooks on the market about this subject!
The cheap 'fix' for your problem is to reduce the time interval for updates - e.g. instead of updating the physics in 33ms steps (~30fps), try updating in 16ms steps (~60fps). This won't prevent the problem, but it will make it much less likely to occur. Halving the time step will also double the time the processor has to spend doing physics updates!
If you use the cheap fix, the time step which will work best for you will be determined by how frequently collisions occur - more collisions means smaller time steps. How frequently collisions occur basically depends on how fast the circles tend to move and their population density (how much of a given area is filled by circles).
UPDATE: A little more info on the 'proper' approach.
The update would go something like this:
Start updating a frame. Let's say we want to update as far as time tF.
For every pair of circles, work out when you would expect a collision to occur (ignoring all the other circles). Let's call this time tC.
Find the smallest value of tC. Let's say this is for the collision between circles A and B, and let's call that collision cAB.
If tC <= tF, update all of the circles up to time tC. Otherwise, go to step 6.
Resolve collision cAB. Go back to step 2!
Update all the circles to time tF.
As you might imagine, this can get quite complicated. Step 2 can be quite tricky (and coputationally expensive) for non-circular objects (especially once you include things like angular momentum, etc.) although there are a lot of tricks you can do here to speed it up. It's also basically impossible to know how many times you'll be looping between steps 2 and 5.
Like I said, doing good physics simulation is hard. Doing it in real-time is even harder!

Categories

Resources