Fast moving bodies miss the collision sometimes in Box2d, AndEngine - android

I have a Fast Moving Body(A) which is dynamic. It is supposed to collide with another Body(B). A collides with B, but sometimes it passes the Body B without collision. This is totally random behavior. I must have that collision. Kindly guide why it is acting like this, randomly.

The effect of one object passing through another due to large movement in a single timestep is called tunneling.
Box2D uses Continuous Collision Detection between dynamic and static objects to solve this problem. However, your case (dynamic v.s. dynamic) isn't automatically handled, so it's just a random dice throw whether your objects happen to be in colliding positions at the exact moment the collisions are evaluated.
From the Box2d Manual:
Normally CCD is not used between dynamic bodies. This is done to keep
performance reasonable. In some game scenarios you need dynamic bodies
to use CCD. For example, you may want to shoot a high speed bullet at
a stack of dynamic bricks. Without CCD, the bullet might tunnel
through the bricks.
Fast moving objects in Box2D can be labeled as bullets. Bullets will
perform CCD with both static and dynamic bodies. You should decide
what bodies should be bullets based on your game design. If you decide
a body should be treated as a bullet, use the following setting.
bodyDef.bullet = true;
The bullet flag only affects dynamic bodies.
Box2D performs continuous collision sequentially, so bullets may miss
fast moving bodies.

Related

Is there a faster algorithm for collision detection?

I'm writing this game on Android where I have a bunch of characters moving around who collide with each other. Everything works fine but when I get passed a certain number of characters on the screen at the same time, the performance of the app gets hit severely. I did my tests and drawing is not causing the low frame rate, it is the algorithm for collision detection, since every time they move they have to check their location to all the other characters. So currently I'm just looping through them all for each character. Is there a way to improve on this? Is there a performance trick to collision detection on a big number of objects that I don't know about?
Yes, there is a technique based on a first broad-phase and second narrow-phase colission detection.
I'll quote some paragraps from: Beginning Android Games, by Mario Zechner.
Broad phase: In this phase we try to figure out which objects can
potentially collide. Imagine having 100 objects that could each
collide with each other. We’d need to perform 100 * 100 / 2 overlap
tests if we chose to naively test each object against each other
object. This naive overlap testing approach is of O(n^2) asymptotic
complexity, meaning it would take n^2 steps to complete (it actually
finished in half that many steps, but the asymptotic complexity
leaves out any constants). In a good, non-brute-force broad phase, we
try to figure out which pairs of objects are actually in danger of
colliding. Other pairs (e .g., two objects that are too far apart for
a collision to happen) will not be checked . We can reduce the
computational load this way, as narrow-phase testing is usually pretty
expensive.
Narrow phase: Once we know which pairs of objects can potentially
collide, we test whether they really collide or not by doi ng an
overlap test of their bounding shapes.
The broad phase involves dividing the world in large cells, making some sort of grid.
Each cell has the exact same size, and the whole world is covered in cells. If two objects are not in the same cell, a narrow phase for those two objects is not needed.
Quote once again:
All we need to do is the following:
Update all objects in the world based on our physics and controller step.
Update the position of each bounding shape of each object according to the object’s position. We can of course also include the orientation and scale as well here.
Figure out which cell or cells each object is contained in based on its bounding shape, and add it to the list of objects contained in those cells.
Check for collisions, but only between object pairs that can collide (e.g., Goombas don’t collide with other Goombas) and are in the same cell.
This is called a spatial hash grid broad phase, and it is very easy to implement. The first thing we have to define is the size of each cell. This is highly dependent on the scale and units we use for our game’s world.
It also depends on the bounding shape you're using. A simple rectangle or circle around the characters and it's euclidean distance is one simple thing to calculate, but a finer shape (including details as "the head", "the legs" with little additional bounding shapes) will be more a lot more computationally expensive to calculate.
If all objects are free to move to any part of the screen, then the best you can do is your O(n^2) algorithm. You can improve it by a constant factor by realizing that when you check if object A collides with object B, then you don't have to later check if object B collides with object A.
enclose each character within a fixed size square. Before you check for character collision, check if the squares in which they are enclosed collide. If and only if the squares collide, there would be a chance for the characters to collide. Now checking for squares collision is easy as you have to just compare the x & y co-ordinates.
Dividing into a broad phase and narrow phase as Federico suggests only helps if your collision detection algorithm is expensive, i.e. it's not a simple bounding box.
Fortunately there are other options.
You could try a collision mask technique. Since you don't seem to be limited by rendering speed, render a bounding box for each object into a hidden bitmap. Before rendering the next object, check the pixels at the four corners of its bounding box to see if they have already been written. You can even use a different colour for each object so that the colour tells you which object the collision was with.
Another popular trick is to simply not do every collision check every frame. For example, games like Super Mario Bros actually only check for collisions between the player and enemies every other frame. You can do a more advanced version where you check all objects in a round-robin fashion, doing as many as it can per frame. When things get busy each object might only be checked every other or even every third frame, but the player is unlikely to notice. This works best if your objects are not moving so fast that they can pass through each other one only one frame of collision.

How to remove a physical body in AndEngine

I Added the coins on the track of user by creating a Sprite, which i kept in a Body. The problem is when the player collide with coin, the coin removed but it takes a jerk for nano second. I want the player to run smooth even when he collides with the coin.
You are correct, the problem is due to Box2D. Obviously, removing a body takes some time and causes some delay. If you don't plan to have a very large number of bodies you can just keep them the whole time, you can attach a sensor to the body. Sensor is a special kind of fixture that does not cause collisions with other bodies but you can find out whether the bodies are touching. This way you could keep the coins in their place and only remove the Sprite so that the coin will disappear without the overhead caused by removing a body.
See the Box2d manual here:
http://www.box2d.org/manual.html#_Toc258082972
Another thing is collision filtering, although I am not certain whether the isTouching() method would return true if the collision bits are set up appropriately, so you'll have to try that. There is a nice tutorial here:
http://www.iforce2d.net/b2dtut/collision-filtering

Collision detection for rotated bitmaps on Android

I need pixel-perfect collision detection for my Android game. I've written some code to detect collision with "normal" bitmaps (not rotated); works fine. However, I don’t get it for rotated bitmaps. Unfortunately, Java doesn’t have a class for rotated rectangles, so I implemented one myself. It holds the position of the four corners in relation to the screen and describes the exact location/layer of its bitmap; called "itemSurface". My plan for solving the detection was to:
Detect intersection of the different itemSurfaces
Calculating the overlapping area
Set these areas in relation to its superior itemSurface/bitmap
Compare each single pixel with the corresponding pixel of the other bitmap
Well, I’m having trouble with the first one and the second one. Does anybody has an idea or got some code? Maybe there is already code in Java/Android libs and I just didn’t find it.
I understand that you want a collision detection between rectangles (rotated in different way). You don't need to calculate the overlapping area. Moreover, comparing every pixel will be ineffective.
Implement a static boolean isCollision function which will tell you is there a collision between one rectangle and another. Before you should take a piece of paper do some geometry to find out the exact formulas. For performance reasons do not wrap a rectangle in some Rectangle class, just use primitive types like doubles etc.
Then (pseudo code):
for (every rectangle a)
for (every rectangle b)
if (a != b && isCollision(a, b))
bounce(a, b)
This is O(n^2), where n is number of rectangles. There are better algorithms if you need more performance. bounce function changes vectors of moving rectangles so that imitates a collision. If the weight of objects was the same (you can aproximate weight with size of the rectangles), you just need to swap two speed vectors.
To bounce elements correctly you could need to store auxiliary table boolean alreadyBounced[][] to determine which rectangles do not need a change of their vectors after bounce (collision), because they were already bounced.
One more tip:
If you are making a game under Android you have to watch out to not allocate memory during gameplay, because it will faster invoke GC, which takes a long time and slow downs your game. I recommend you watching this video and related. Good luck.

How to make a consistant game loop

So in my game my View gets drawn an inconsistent rates. Which in turn makes it glitchy. Ive been running into alot of problems with the invalidate(); meathod. Any simple ideas- Everywhere i look I get thrown up on by tons of intense code.
You haven't provided us with much information, specifically code.
A few things you could do are:
Set the initial frame rate to the lowest value you observe your application runs at, i.e., if currently set to 1/60, but the frame rate continuously dips to 1/30, set to 1/30 etc.
Rework your drawing calls to be more efficient.
Try to combine multiple transformations into a single transformation by multiplying matrices, i.e. if you need to scale, translate, and rotate, multiply those three matrices together and apply that single transformation to the vertices instead of applying three separate transformations.
Try not to iterate through entire lists/arrays if unnecessary.
Attempt to use the lowest level / most primitive structure possible for anything you have to process in the loop to avoid the overhead of unboxing.
[edit on 2012-08-27]
helpful link for fixing you timestep: http://gafferongames.com/game-physics/fix-your-timestep/
It sounds like your game loop doesn't take into account the actual time that has passed between iterations.
The problem is the assumption that there is a fixed amount of time between loop iterations. But this time can be variable depending on the number of objects in the scene, other processes on the computer, or even the computer itself.
This is a common, somewhat subtle, mistake in game programming, but it can easily be remedied. The trick is to store the time at the end of each draw loop and then take the difference of the last update with the current time at the start. Then you should scale all animations and game changes based on the actual elapsed time.
I've wrote more about this on my blog a while back here: http://laststop.spaceislimited.org/2008/05/17/programming-a-pong-clone-in-c-and-opengl-part-i/
Part II specifically covers this issue:
http://laststop.spaceislimited.org/2008/06/02/programming-pong-in-c-and-opengl-part-ii/

Whats the best way to do character animations with Box2D?

I am developing a 2D, underwater, action-RPG for Android, using Box2D as the physics engine, mainly for collision detection, collision response and movement of in-game characters within an environment comprised of walls, rocks, and other creatures.
I have tried two different approaches for implementing character animations using Box2D, and have found issues with both. As I'm new to Box2D and physics engines, I would appreciate a recommendation on how these things should best be done.
An example of an animation I am trying to do is as follows:
A fish wants to attack another fish, so does the following:
1) Move towards target at speed
2) Take a bite out of target creature
3) Turn and flee, back to where the attack began
4) Turn back to face the target, ready for another attack
The two approaches I've tried are:
A) Apply a force to the attacker (using body.applyForce() ) to move it towards the target, then another force to move it back again, after the collision
Problems:
* Frequently the attacker hits the target and bounces off and goes hurtling back at great speed, and bounces off walls, everywhere. The speed is pretty random, depending on where it impacts the target, the mass of the target, etc. It breaks the animation and looks terrible.
* It's very hard to figure out what forces should be applied to the attacker and when, to simulate a particular animation in a physics world so it looks realistic
B) Directly set the position of the attacker (using body.setTransform() ) to move the attacker to the correct position, as it moves forwards each step, then moves back again.
Problems:
* Directly setting the position allows the attacker to ignore collisions with walls and other creatures, so getting stuck in a wall is common
* If the player is attacking, I update the world origin as the player moves, to keep the player mid-screen. This works well, except when I start an animation, as I don't want the screen to follow the animation, but only the movement component of the existing velocity, which I don't know, as I'm overriding the Box2D forces/velocities when I set the position. It's possible to do this I'm sure, but difficult - maybe I'm missing something obvious.
Should I be monitoring the collisions? Overriding the collision response?? Something else?
So, how would you recommend I approach this problem?
I'm only used to work with Farseer, but Farseer is a pretty direct port from Box2D, so I hope this answer is still helpful.
Next to applying force and teleporting you can also set the linear movement speed of a body. This way you can have the fish move towards the player without applying force. You should capture the collision events from the fish body and compare in each event if the fish has hit the player, then set false/NoCollision in the collision event with the player so that it doesn't bounce of. Now set the fish body to ignore any collisions with the player body and use a fixed joint to stick the fish to the player. You can now play your bite animation.
After the bite animation you want to disengage the fish. Start your flee animation, remove the joint and teleport the fish to the edge of the player body (so that it's not colliding with it). After that re-enable collisions between the fish and the player body and send the fish away from the player (either by setting linear movement speed again, or for a nice bounce effect via force.

Categories

Resources