Impulse based physics - Stacking heavy object on light object - physics

I'm developing an impulse based physics engine, but I have a problem with objects of large mass difference.
At each frame the engine applies impulses to handle collisions. The impulses are applied over a number of iterations, between each pair of colliding objects. This works well if the objects are about the same mass.
But the problem is, that when placing a heavy object, on top of a light object, the heavy object will force then light object into the ground.
The cause of the problem is, that the impulses applied between the two objects is too small, so even over a number of iterations, it will not be enough to counter the gravity on the heavy object.
I believe there are ways to accurately calculate the needed impulses, but I fear it's too complicated? So mostly I'm looking for some tricks to counter this problem, but not changing the way the engine works.
Thanks for any ideas!

Google for 'Shock propagation', the basic idea is that you sort your contacts in the direction of gravity (usually along the 'y' axis) and during contact resolution you freeze the lower bodies (assign to them infinite mass, that is, invMass = 0.0f and invInertiaTensor should be a zero matrix) so that they don't 'sink'. I haven't implemented that, i'm struggling with my own crappy physics engine.

Related

SKPhysicsBody optimization

I have a 2D sidescrolling game. Right now, in order to jump, the player must be touching the ground. Therefor, I have a boolean, isOnGround, that is set to YES when the player collides with a tile object, and no when the player jumps. This generates a LOT of calls to didBeginContact method, slowing down the game.
Firstly, how can I optimise this by using one big physics body for the tiles on the floor (for example clustering multiple adjacent tiles into one single physics body)?
Secondly, is this even efficient? Is there a better way to detect if the play is on the ground? My current method opens up a lot of bugs, for example wall jumping. If a player collides with a wall, isOnGround becomes YES and allows the player to jump.
Having didBeginContact called numerous times should in no way slow down your game. If you are having performance issues, I suspect the problem is probably elsewhere. Are you testing on device or simulator?
If you are using the Tiled app to create your game map, you can use the Objects Layer to create a individual objects in your map which your code can translate into physics bodies later on.
Using physics and collisions is probably the easiest way for you to determine your player's state in relation to ground contact. To solve your wall issue, you simply make a wall contact a different category than your ground. This will prevent the isOnGround to be set to YES.
You could use the physics engine to detect when jumping is enabled, (and this is what I used to do in my game). However I too have noticed significant overhead using the physics engine to detect when a unit was on a surface and that is because contact detection in sprite kit for whatever reason is expensive, even when collisions are already enabled. Even the documentation notes:
For best performance, only set bits in the contacts mask for
interactions you are interested in.
So I found a better solution for my game (which has 25+ simultaneous units that all need surface detection). Instead of going through the physics engine, I just did my own surface calculation and cache the result each game update. Something like this:
final class func getSurfaceID(nodePosition: CGPoint) -> SurfaceID {
//Loop through surface rects and see if position is inside.
}
What I ended up doing was handling my own surface detection by checking if the bottom point of my unit was inside any of the surface frames. And if your frames are axis-aligned (your rectangles are not rotated) you can perform even faster checks to see if the point is inside the frame.
This is more work in terms of level design because you will need to build an array of surface frames either dynamically from your tiles or manually place surface frames in your world (this is what I did).
Making this change reduced the cpu time spent on surface detection from over 20% to 0.1%. It also allows me to check if any arbitrary point lies on a surface rather than needing to create a physics body (which is unnecessary overhead). However this solution obviously won't work for you if you need to use contact detection.
Now regarding your point about creating one large physics body from smaller ones. You could group adjacent floor tiles using a container node and recreate a physics body that fits the nodes that are grouped. Depending on how your nodes are grouped and how you recycle tiles this can get complicated. A better solution would be to create large physics bodies that just overlap your tiles. This would reduce the number of total physics bodies, as well as the number of detections. And if used in combination with the surface frames solution you could really reduce your overhead.
I'm not sure how your game is designed and what its requirements are. I'm just giving you some possible solutions I looked at when developing surface detection in my game. If you haven't already you should definitely profile your game in instruments to see if contact detection is indeed the source of your overhead. If you game doesn't have a lot of contacts I doubt that this is where the overhead is coming from.

Using Pathfinding, such as A*, for NPC's & character without Tiles

I've been reading a book called "iOS Games by Tutorials" (recommend it to anyone interested in making iPhone games) & I'm learning how to make Tiled Maps with Sprite Kit with an overhead view (like the legend of zelda link's awakening). So far, I have made a tiled map using tiles that are 32x32, placed the player character & several NPC's into the world. Even made the NPC's randomly move around the map, though the way it teaches in the book is having them move from tile to tile (any of the 8 tiles surrounding the NPC at any time - if a tile has some property such as categoryBitMask then it won't move to that tile).
I am going to change NPC movement to physics-based (which is its own problem) just like the player character has right now (which means NPC's will collide with objects that have a physicsBody like the player character does). It's more fluid & dynamic.
But here is where the question begins. I want to implement Pathfinding (such as the A* algorithm) into the NPC & player character movement due to the map containing buildings, water, trees, etc. with their own physicsBodies. It's one thing to limit NPC's random movement or to force them to walk a predetermined path (which will kill the point of this game), but it's another to have to tap the screen very often to have the player character avoid all the buildings/trees he has to walk past. I don't want to use a grid system. Is it possible to implement some pathfinding algorithm into x,y coordinates? Is this more resource intensive? Could you share your thoughts about this?
Thank you.
This is a very interesting topic.
There are algorithms for finding paths in continuous spaces. For example, you can use a potential based method with the objective having a very low potential and obstacles being "hills" (perhaps infinitely high, although this requires a bit of care). The downside of potential methods is that you have to take special precautions to keep them from getting stuck at a local minimum. Situations like this
P
+----+
| M|
| |
+ ---+
Where M is a monster trying to get to the player, P can occur. In the example, the monster is at a local minimum, and it would have to go to a higher potential in order to get out the door at the lower left of the building. A variant of potential algorithms (in fact, it's often useful to reduce it to one), is to assign anti-gravity to obstacles and gravity to objectives. This is also somewhat non-deterministic and requires special precautions to avoid getting "stuck".
As #rickster points out, SpriteKit provides an SKFieldNode class that can help you implement a potential based solution.
Other approaches include "wall following" (for example, Pledge's algorithm) and are useful for finding your way around in a maze like environment.
One drawback to continuous methods is that NPC movement will often seem a bit unnatural -- for example, even if our monster in the example above is able to decide that it's at a local minimum and increase the "temperature" of it's search (that is, make larger moves, perhaps at random, against the potential gradient), it will bounce around instead of going straight for the door.
An alternative to searching in continuous spaces is to quantize the space. A simple method is to tile it, cover it with polygons, or represent it as a quadtree. Essentially, you want to have a way of mapping every point in the continuous space to a vertex on a graph representing the quantized space. At this point, graph search algorithms like A* and friends are applicable.
Graph search is somewhat resource intensive, but for a 2d zelda like game, it should be doable on a mobile device, especially with various optimizations like only "waking up" NPCs that are within a certain distance of the player (think aggro).
This page is a bit thin on implementation details, but it'll give you the right terms to google.
As always, start simple and iterate. Tiling is incredibly easy, and will let you experiment with the graph search method before optimizing.

Angry bird Physic impact/collision

How do I create a motion impact/collision like angry bird. When the object hit the box and wood, their interaction and the flow of the animation will to the right position. I need to learn from scratch how to build it. I need the basic of physic and concept
Example image:
So far, What i think so far is. Upon impact, I will apply
Law of Restitution
object 1 velocity = e(ball velocity)
I will take the direction of the ball and make the object 1 to rotation 90% against the ball.
if ball ---> direction. my end result for object 1 will be 90 degree against it. so it will become
|____| it will turn into this.
So far it seen right. But I am unsure how to interact with object 2. Do I repeat step and 2. Whereby I passed the velocity and direction to object 2. so it will rotation 90 degree again?
This is what I have gather so far. Any suggest that I am moving to right direction will be good.
For collision part. I intend to use AABB. and rotation AABB.
AngryBirds used Box2D physics when I opened About page inside game.
Box2D is open source physics engine.
Most physics engines are based on impulses. They sum impulses and re-calculate velocities.
The most complex and import part is what happens when collision occur.
Physic Engine detect all collisions and use Solver function. Solver is heart and sole of phsyics engine. Solve adds additional impulses to "solve" collision.
Solver usually has form of function that takes collision island (list of colliding objects: often 2 objects) and return force or impulse to be applied to each object.
Most modern engines are impulse based.
So most important part of physics engine to learn and understand is Solver function. But solver could be more complex entity then function.

Calculating inertia for a multi-shape rigid body

I figured someone probably asked this question before but I wasn't able to find an answer.
I'm writing a physics library for my game engine (2d, currently in actionscript3, but easily translatable to C based languages).
I'm having problems finding a good formula to calculate the inertia of my game objects.
The thing is, there are plenty of proven formulas to calculate inertia around a centroid of a convex polygon, but my structure is slightly different: I have game-objects with their own local space. You can add convex shapes such as circles and convex polygons to this local space to form complex objects. The shapes themselves again have their own local space. So there are three layers: World, object & shape space.
I would have no problems calculating the inertia of each individual polygon in the shape with the formulas provided on the moments of inertia Wikipedia article.
or the ones provided in an awesome collision detection & response article.
But I'm wondering how to relate this to my object structure, do I simply add all the inertia's of the shapes of the object? That's what another writer uses to calculate the inertia of triangulated polygons, he adds all the moments of inertia of the triangles. Or is there more to it?
I find this whole inertia concept quite difficult to understand as I don't have a strong physics background. So if anyone could provide me with an answer, preferably with the logic behind inertia around a given centroid, I would be very thankful. I actually study I.T. - Game development at my university, but to my great frustration none of the teachers in their ranks are experienced in the area of physics.
Laurens, the physics is much simpler if you stay in two dimensional space. In 2D space, rotations are described by a scalar, resistance to rotation (moment of inertia) is described by a scalar, and rotations are additive and commutative. Things get hairy (much, much hairier) in three dimensional space.
When you connect two objects, the combined object has its own center of mass. To calculate the moment of inertia of this combined object, you need to sum the moments of inertia of the individual objects and also add on offset term given by the Steiner parallel axis theorem for each individual object. This offset term is the mass of the object times the square of the distance to the composite center of mass.
The primary reason you need to know the moment of inertia is so that you can simulate the response to torques that act on your object. This is fairly straightforward in 2D physics. Rotational behavior is an analog to Newton's second law. Instead of F=ma you use T=Iα. (Things once again are much hairier in 3D space.) You need to find the external forces and torques, solve for linear acceleration and rotational acceleration, and then integrate numerically.
A good beginner's book on game physics is probably in order. You can find a list of recommended texts in this question at the gamedev sister site.
For linear motion you can just add them. Inertia is proportional to mass. Adding the masses of your objects and calculating the inertia of the sum is equivalent to adding their individual inertias.
For rotation it gets more complicated, you need to find the centre of mass.
Read up on Newton's laws of motion. You'll need to understand them if you're writing a physics engine. The laws themselves are very short but understanding them requires more context so google around.
You should specifically try to understand the concepts: Mass, Inertia, Force, Acceleration, Momentum, Velocity, Kinetic energy. They're all related.

iOS - How to detect if two or more objects collide

How can i detect if two or more objects collide?
I would like to use only default frameworks, such Core Graphics. Or i have to use Box2d or Cocos2d?
EDIT
You're right, the question isn't really clear.
So this is the situation :
i have multiple UIImageView which move with the accelerometer, but i want that when two or more images collides these isn't overlap each others. Is it clear?
Probably you want a multi-step process.
First, define a "center" and "radius" for each object, such that a line drawn around the center at the selected radius will entirely encompass the object without "too much extra". (You define how hard you work to define center and radius to prevent "too much".)
An optional next step is to divide the screen into quadrants/sections somehow, and compute which objects (based on their centers and radii) lie entirely within one quadrant, which straddle a quadrant boundary, which straddle 4 quadrants, etc. This allows you to subset the next step and only consider object pairs that are in the same quadrant or where one of the two is a straddler of one sort or another.
Then, between every pair of objects, calculate the center-to-center distance using the Pythagorean theorem. If that distance is less than the sum of the two objects' radii then you have a potential collision.
Finally, you have to get down and dirty with calculating actual collisions. There are several different approaches, depending on the shape of your objects. Obviously, circles are covered by the prior step, squares/rectangles (aligned to the X/Y axes) can be computed fairly well, but odd shapes are harder. One scheme is to, on a pair of "blank" canvases, draw the two objects, then AND together the two, pixel by pixel, to see if you come up with a 1 anywhere. There are several variations of this scheme.
As mentioned, your question is pretty vague, and therefore difficult to answer succinctly. But to give you some ideas to go by, you can do this with core animation, though some 3rd party gaming engines/frameworks may be more efficient.
Essentially, you create a timer that fires quite often (how often would depend on the size of the objects you're colliding and their speed - too slow and the objects can collide and pass each other before the timer fires - math is your friend here).
Every time the timer fires you check each object on screen for collisions with the others. For efficiencies sake you should ensure that you only check each pair once - ie. if you have A,B,C,D objects, check A & D but not D & A.
If you have a collision handle it however you want (animation/points/notification/whatever you want to do).
There's way too much to cover here in a post. I'd suggest checking out the excellent writeup on the Asteroids game at cocoawithlove, especially part 3 (though not iOS the principles are the same):
http://cocoawithlove.com/2009/03/asteroids-style-game-in-coreanimation.html