# Physics problems: bodies get stuck in each other etc

 Topics: Developer Forum Wiki Link: [discussion:82336]
 BramDeMoor Jan 28, 2010 at 7:38 PM Hi all! Only one more month left before my little game "Flight of the Strihuhn" is released (see http://farseerphysics.codeplex.com/Thread/View.aspx?ThreadId=80459) But I'm having some problems that I can't work out on my own. Sometimes the physics behave really strange. Some examples: When the player geom collides with a platform in the terrain, he sometimes rebounds with an extremely high force The player often gets stuck in terrain, platforms and other game objects Similar issues with other objects - getting stuck, rebounding, etc. Some more background info: most geoms, including the player geom, are simple circles or rectangles. They don't move at a very high speed - it's all just very basic. Some code snippets... Updating the simulator: ```PhysicsSimulator.Update((float)gameTime.ElapsedGameTime.TotalSeconds); ``` Code to create a circle body and geom: ``` protected void CreateCircleBodyAndGeom(float radius, float mass) { Body = BodyFactory.Instance.CreateCircleBody(physicsSimulator, radius, mass); Geom = GeomFactory.Instance.CreateCircleGeom(physicsSimulator, Body, radius, 20); Body.LinearDragCoefficient = defaultLinearDrag; } ``` Part of the move code for the player: ``` if (input.CurrentKeyboardState.IsKeyDown(Keys.Up)) { Body.ApplyForce(new Vector2(0, -upwardForce)); } else if (input.CurrentKeyboardState.IsKeyDown(Keys.Down)) { Body.ApplyForce(new Vector2(0, downwardForce)); } ``` Tomorrow, I will post an in-game video that clearly shows these problems. I can also provide more code snippets, but I just don't know where to look at the moment. :( Thanks in advance for helping me out. These problems are really driving me nuts, so anyone who shines a light here will be mentioned in the game credits. genbox Coordinator Jan 28, 2010 at 9:22 PM I'm not really able to see what could be wrong from the code snippets you posted. What is the magnitude of mass are you using, and what is the magnitude of the forces are you applying? You might be experiencing tunneling - we don't have any CCD algorithms in FPE 2.x, so tunneling will happen at high velocities (or small objects, or infrequent physics updates). You might want to enable debug view found in the samples. It is a good visual indicator of what happens in the eyes of the physics engine. You could attach a video of that if possible. I do have a request regarding the video; I've asked a lot of users to post videos of their problems - the problem with this is that they upload them to youtube and named them "Farseer Physics bug" or something like that. 99% of the cases it is not a FPE related bug, but something in the game itself. I would really appreciate if you named the video appropriately. Would like people to see real videos of FPE when searching youtube and not 1000 buggy games that uses FPE. BramDeMoor Jan 29, 2010 at 6:50 AM Thanks for the quick reply! I understand your concerns about the video. I was already planning to enable debug view and upload it to a less public video hosting site - I'll make sure to give it an appropriate name. I'm sure it's in the game itself, since I'm doing only basic stuff which is done in the examples too (and they run fine). I'll post the values of the masses and forces when I get back from work. BramDeMoor Jan 29, 2010 at 12:47 PM Here's a video that shows the problems: http://www.metacafe.com/watch/4091930/physics_errors_in_my_game/ BramDeMoor Jan 29, 2010 at 6:26 PM `Here are the forces, masses etc. I like to keep them all in one top-level class so I can manage the balance from one place.` The drag coefficients are linked to the LinearDragCoefficient property The weights are linked to the mass property of the body The forces are applied using Body.ApplyForce (during input or update methods) The forces seem a little high at first sight... ``` public static class EntityDragCoefficients { public const float FallingSpike = 6f; public const float Player = 4.4f; } public static class EntityWeights { public const int FallingSpike = 20; public const int Balloon = 6; public const int Player = 13; } public static class EntityForces { public const int BalloonUpwardForce = 530; public const int PlayerHorizontalForceAmount = 1000; public const int PlayerUpwardForceStandard = 500; public const int PlayerDownwardForce = 1500; public const int PlayerUpwardForce = 2000; public const float WindForce = 6f; public const float Gravity = 35f; } ``` genbox Coordinator Jan 29, 2010 at 8:42 PM Well, it takes a high force to move a heavy object. If you lower your mass, it will require lower force values to move it, however, it should not be a problem in this case. Are you using the Distance Grid (it is the default) or the SAT narrow phase collider? BramDeMoor Jan 29, 2010 at 9:49 PM I do not set any properties on the PhysicsSimulator object (except for the gravity), so I think it's the distance grid with its default settings. genbox Coordinator Jan 29, 2010 at 9:54 PM Ok, that narrows down the problem. I think I can see that you only have vertices at the ends of the platforms. You need vertices on the edges of the platforms too, this is very important when using the Distance Grid narrow phase collider. Either you use the CreateRectangleGeom() method on the GeomFactory or use Vertices.SubDivideEdges() (If I remember correctly) manually on your vertex collections. Another thing is to tweak the Collision Grid Cell Size value of the distance grid. Lower it to create a more fine grid - that improves the precision of the collisions, but it also takes a lot more time to calculate the grids. The first thing should fix it tho, try it out and see if it works. BramDeMoor Jan 30, 2010 at 1:47 PM I solved most of the issues by using SubDivideEdges. The edges of the polygons created with the PolygonCreationAssistance such as the platforms and the terrain are now further divided (more 'dots' in the debug view). I'll have to test it some more, but so far I couldn't trigger one of the bugs anymore, so that's great! I was not able to find the Grid Cell Size setting however. I did find a property with that on the Geom class but it doesn't have a public setter. Thanks for the help! :-) genbox Coordinator Jan 30, 2010 at 2:43 PM Sounds great. The grid cell size can be given to the GeomFactory's create methods. BramDeMoor Feb 7, 2010 at 12:55 PM FYI: I was still having some problems, but I think I found the cause. It has something to do with "infrequent physics updates" as genbox suggested in his first reply. There's something wrong with the time management of my game, which causes the physics engine to be updated with a too large interval. Often, collisions are detected when it's already too late (the bodies are already stuck in each other), which results in the behaviour that I described. Currently, I use the following simple workaround: ```IsFixedTimeStep = false; ``` I'm not entirely sure if this is the way to go - I need to do some more testing and reading first. The following articles explain some of the concepts of game timing. BramDeMoor Feb 26, 2010 at 4:10 PM Another update. Even after all the previous fixes, I was still having the same issues (but in a less frequent rate). I solved this by using some sort of object caching, similar to the approach suggested in the farseer documentation. The objects that created the problems were "spike spitters", objects that spawn spikes with a certain interval. Each time such an object created a spike (just a simple circle body/geom), and added it to the physics simulator, the game seemed to run out of sync a little bit, creating all kinds of issues. My solution: Each spike spitter has 3 pre-created spikes. When a spike should normally dissapear from the level, I just recycle it by setting its state (position, speed, etc) to the initial values, allowing it to be spawned infinite times. So basically, no new spikes are added to the simulation or removed from it during the game. It's just a quick fix... Theoretically, I should be able to create simple physics objects at runtime without any performance issues... But anyway, for this game, this problem is solved. So far for the good news :-)     There's one issue remaining... Sometimes, objects can still get stuck... But in a different way. Previously, it happened that objects completely overlapped each other, and then got stuck inside, due to the reasons listed in this thread. But now it's a different story - There's no overlap, no performance issues, but the objects seem "glued" together anyway.  Here's an image showing the problem: http://img203.imageshack.us/img203/8438/stuckscreen.png In the image, it's the player object that is stuck. Sometimes, the balloon object gets stuck too, in exactly the same way.  This always happens with instances of the "TerrainLump" class, a generic type I use for all terrain in the game. Here's the code that generates the body and geom for the TerrainLump:   ``` protected void CreateTerrainBodyAndGeom() { var data = new uint[Texture.Width * Texture.Height]; //Transfer the texture data to the array Texture.GetData(data); // get a set of vertices from a texture and extract those vertices into a Vertices structure var pca = new PolygonCreationAssistance(data, Texture.Width, Texture.Height) { HullTolerance = 10, //60f of 30f HoleDetection = false, //f MultipartDetection = false, //f AlphaTolerance = 20, //20 }; terrainVertices = Vertices.CreatePolygon(ref pca)[0]; terrainVertices.SubDivideEdges(10); polygonOrigin = terrainVertices.GetCentroid(); Body = BodyFactory.Instance.CreatePolygonBody(physicsSimulator, terrainVertices, 1); Body.IsStatic = true; // use AutoDivide to find up to 25 convex geoms from a set of vertices GeomFactory.Instance.CreateSATPolygonGeom(physicsSimulator, Body, terrainVertices, 250); // 250 of 550 ExtraPositionCorrection = new Vector2(polygonOrigin.X, polygonOrigin.Y); // WHY: Applies ExtraPositionCorrection Position = new Vector2(0,0); } ``` Note that I have some numbers in comments - these are other values I experimented with for the parameters of the functions. Thanks in advance for any suggestions... I'm very close to a release, and this is in fact the last annoying issue I still have to solve. BramDeMoor Mar 2, 2010 at 11:30 PM Normally, my game was planned to be released today. In the last few days, a new bug has emerged though. I already tried changing every possible parameter and still don't know what's causing the problem... I recorded a few of the bugs and posted them here: http://www.metacafe.com/watch/4246361/physics_errors_in_my_game2/ These are just the 'little' bugs though, often the balloons or the player rebound with a very high force when colliding with other objects and end up getting stuck in terrain, platforms etc. The physics bugs also get worse after some time. When the level has just started, there aren't a lot of bugs. However, after a while, everything starts freaking out. If anyone has an idea what's causing these problems, I'd be very grateful! :-)