Collision Handling Between Circle and Line Segments - xna

I'm implementing a small game and am having trouble getting the physics working properly.
In this game, there is one ball (a circle which moves from frame to frame, and may change radius) and several walls (line segments which also change and move from frame to frame). I can detect collisions properly, and making the ball bounce off in the correct direction is no problem.
Difficulties arise in situations where the ball intersects a line in one frame, then intersects it again in the subsequent frame, causing a double bounce. I could move the ball back along the normal of the line until it is in a valid position, but this causes really weird behaviour when the line in question is being hit along its axis (imagine a ping pong ball falling down on an upright toothpick and suddenly shifting aside so that it is on one side of the toothpick...). There are also a few issues when the ball intersects more than one line in a given frame (imagine four lines together making a rectangle and the ball intersecting the corner of said rectangle) -- which direction should it bounce off? In which direction should it shift?
I don't really have a specific question, but am looking for tips or some useful tutorials. All the 2D ones I've managed to find so far only cover rectangle intersections.
I'm using XNA if it makes any difference.
Thanks,
Cameron

This is an universal problem with most physics libraries. If you google for "penetration depth" (together with "physics", I suggest, or you might find something entirely different :D) you will find that even these libraries use tricks like yours.
There are two solutions to this:
The cheap one is to increase your update frequency. Move objects in 10 smaller steps instead of a single big one and you will have less penetration, so fixing it by offsetting the ball away from the wall will be less visible.
The expensive one is continuous collision detection. There are algorithms that can tell you, given a moving and a stationary object, the exact point in time both will will intersect. Google "swept sphere rectangle intersection" to find some of these.
You can then update like this: ball needs to move by 1.0 units. Check for collision. Collision occurs after 0.25 units, so move ball by 0.25 units, calculate reflection vector (so the ball bounces off the wall), repeat collision check with remaining 0.75 units (until you know the final position of the ball). This avoids penetrations entirely and even if your ball is moving so fast that it would normally skip over the wall in a single update, the collision will be detected.

It's generally accepted that, because of the timestep your collisions will intersect past an acceptable point in between updates.
Basically, you have to interpolate back to the point in between the last and current frame where the collision truly happened, move the object back to that point, and then calculate the forces, etc.

Related

SpriteKit collision angle of line and circle is odd

Suppose a circle is enclosed in a diamond, and the circle heads due right. I would expect a series of continual 90 degree angles as the circle draws a square within the diamond.
What I'm seeing, however, is that the circle eventually gets pushed toward the center of the diamond after one or two collisions. What's going on?
The line is set to dynamic -> NO.
The ball gets reflected symmetrically to its angle of approach assuming it's a completely elastic collision. That means, to get the behavior you are looking for, the ball would need to approach exactly from one line mid-point to the next without any loss of energy.
Sprite Kit's physics engine will not be able to handle these exact values. The energy after an elastic collision in Sprite Kit is not guaranteed to be conserved. There will be small inaccuracies in the physics engine's floating point calculations. Also the collision itself may not be resolved as a perfect point-to-point reflection, which means the ball might "slide," which will result in the angle of reflection changing.
However I would still expect to see more collisions then just one or two. Make sure the restitution of both objects is set to 1.0 and make sure the ball's linear damping is set to 0. affectedByGravity should obviously be false. Friction should be set to 0. You can try setting usesPreciseCollisionDetection to true.
If you need the behavior you described in you picture to last indefinitely, you will need to set the position and velocity manually.

How to find the normal vector of the contact point between two sprites

I am creating a game where the character can jump in the direction opposite of the surface he lands on. For example if he is on the ground he can only jump up. If he is on a right edge he can only jump left...etc etc.. Currently I have set up my SKNodes into leftWall, rightWall, bottomSurface, topSurface and have a huge if/else... this works but will become way more complicated as I add different surfaces with different angles etc...
I thought a better way to implement this would be to find the normal vector direction at the point of contact between the character sprite and a general wallNode sprites.
Can anyone help me determine A) the point of contact between sprites assuming the character has a circle physics body and the walls are always straight edges. and B) the normal to the contact point
thank you!
I don't think the vector or angle of impact will do you much good as your player's jump would likely be in an ark. As such, hitting the same surface at different points of the player's jump ark would yield different results.
I suggest you use unique category bit masks for your surfaces. A more advanced version of that would be to use only one category and utilize the SKSpriteNode's dictionary property to hold the angle value.
Based on the contact data you can then set the correctly angled jump for your player.

how to effectively use 'deviceMotion' of CMMotionManager to force the ball to move inside circular boundary?

I am using Chipmunk Space Manager.
I have my space setup with one ball and a bunch of segments (512 in my case) joined together to make a circle.
My aim is to force the ball to move in that circle as user moves the device.
The faster user moves the device, faster the ball will move in circle. The ball has to follow all physical laws as well.
I am getting gravity and userAcceleration components from CMMotionManager but unable to make some sense out of it.
I tried applying force manually and that works realistically, but I am unable to move the ball in the circle depending on how much user moved the device.
Like if I put a small ball in a glass and shake the glass, the ball will move in the circular bottom of the glass and comes to rest in the direction of tilt of glass when there is no more external force moving/tilting the glass
I think the easiest way to do it would just be to change the gravity of the space to match the accelerometer. To get smooth circular motion it would probably be best to use a cpSlideJoint with a min dist of 0 and a max dist of the radius of the circle you want to spin it in. It's not possible to make a smooth hollow shape otherwise. You'd have to build it out of many line segments and that might not work very well.

Surface Detection in 2d Game?

I'm working on a 2D Platform game, and I was wondering what's the best (performance-wise) way to implement Surface (Collision) Detection.
So far I'm thinking of constructing a list of level objects constructed of a list of lines, and I draw tiles along the lines.
alt text http://img375.imageshack.us/img375/1704/lines.png
I'm thinking every object holds the ID of the surface that he walks on, in order to easily manipulate his y position while walking up/downhill.
Something like this:
//Player/MovableObject class
MoveLeft()
{
this.Position.Y = Helper.GetSurfaceById(this.SurfaceId).GetYWhenXIs(this.Position.X)
}
So the logic I use to detect "droping/walking on surface" is a simple point (player's lower legs)-touches-line (surface) check
(with some safety approximation
- let`s say 1-2 pixels over the line).
Is this approach OK?
I`ve been having difficulty trying to find reading material for this problem, so feel free to drop links/advice.
Having worked with polygon-based 2D platformers for a long time, let me give you some advice:
Make a tile-based platformer.
Now, to directly answer your question about collision-detection:
You need to make your world geometry "solid" (you can get away with making your player object a point, but making it solid is better). By "solid" I mean - you need to detect if the player object is intersecting your world geometry.
I've tried "does the player cross the edge of this world geometry" and in practice is doesn't work (even though it might seem to work on paper - floating point precision issues will not be your only problem).
There are lots of instructions online on how to do intersection tests between various shapes. If you're just starting out I recommend using Axis-Aligned Bounding Boxes (AABBs).
It is much, much, much, much, much easier to make a tile-based platformer than one with arbitrary geometry. So start with tiles, detect intersections with AABBs, and then once you get that working you can add other shapes (such as slopes).
Once you detect an intersection, you have to perform collision response. Again a tile-based platformer is easiest - just move the player just outside the tile that was collided with (do you move above it, or to the side? - it will depend on the collision - I will leave how to do this is an exercise).
(PS: you can get terrific results with just square tiles - look at Knytt Stories, for example.)
Check out how it is done in the XNA's Platformer Starter Kit Project. Basically, the tiles have enum for determining if the tile is passable, impassable etc, then on your level you GetBounds of the tiles and then check for intersections with the player and determine what to do.
I've had wonderful fun times dealing with 2D collision detection. What seems like a simple problem can easily become a nightmare if you do not plan it out in advance.
The best way to do this in a OO-sense would be to make a generic object, e.g. classMapObject. This has a position coordinate and slope. From this, you can extend it to include other shapes, etc.
From that, let's work with collisions with a Solid object. Assuming just a block, say 32x32, you can hit it from the left, right, top and bottom. Or, depending on how you code, hit it from the top and from the left at the same time. So how do you determine which way the character should go? For instance, if the character hits the block from the top, to stand on, coded incorrectly you might inadvertently push the character off to the side instead.
So, what should you do? What I did for my 2D game, I looked at the person's prior positioning before deciding how to react to the collision. If the character's Y position + Height is above the block and moving west, then I would check for the top collision first and then the left collision. However, if the Character's Y position + height is below the top of the block, I would check the left collision.
Now let's say you have a block that has incline. The block is 32 pixels wide, 32 pixels tall at x=32, 0 pixels tall at x=0. With this, you MUST assume that the character can only hit and collide with this block from the top to stand on. With this block, you can return a FALSE collision if it is a left/right/bottom collision, but if it is a collision from the top, you can state that if the character is at X=0, return collision point Y=0. If X=16, Y=16 etc.
Of course, this is all relative. You'll be checking against multiple blocks, so what you should do is store all of the possible changes into the character's direction into a temporary variable. So, if the character overlaps a block by 5 in the X direction, subtract 5 from that variable. Accumulate all of the possible changes in the X and Y direction, apply them to the character's current position, and reset them to 0 for the next frame.
Good luck. I could provide more samples later, but I'm on my Mac (my code is on a WinPC) This is the same type of collision detection used in classic Mega Man games IIRC. Here's a video of this in action too : http://www.youtube.com/watch?v=uKQM8vCNUTM
You can try to use one of physics engines, like Box2D or Chipmunk. They have own advanced collision detection systems and a lot of different bonuses. Of course they don't accelerate your game, but they are suitable for most of games on any modern devices
It is not that easy to create your own collision detection algorithm. One easy example of a difficulty is: what if your character is moving at a high enough velocity that between two frames it will travel from one side of a line to the other? Then your algorithm won't have had time to run in between, and a collision will never be detected.
I would agree with Tiendil: use a library!
I'd recommend Farseer Physics. It's a great and powerful physics engine that should be able to take care of anything you need!
I would do it this way:
Strictly no lines for collision. Only solid shapes (boxes and triangles, maybe spheres)
2D BSP, 2D partitioning to store all level shapes, OR "sweep and prune" algorithm. Each of those will be very powerfull. Sweep and prune, combined with insertion sort, can easily thousands of potentially colliding objects (if not hundreds of thousands), and 2D space partitioning will allow to quickly get all nearby potentially colliding shapes on demand.
The easiest way to make objects walk on surfaces is to make then fall down few pixels every frame, then get the list of surfaces object collides with, and move object into direction of surface normal. In 2d it is a perpendicular. Such approach will cause objects to slide down on non-horizontal surfaces, but you can fix this by altering the normal slightly.
Also, you'll have to run collision detection and "push objects away" routine several times per frame, not just once. This is to handle situations if objects are in a heap, or if they contact multiple surfaces.
I have used a limited collision detection approach that worked on very different basis so I'll throw it out here in case it helps:
A secondary image that's black and white. Impassible pixels are white. Construct a mask of the character that's simply any pixels currently set. To evaluate a prospective move read the pixels of that mask from the secondary image and see if a white one comes back.
To detect collisions with other objects use the same sort of approach but instead of booleans use enough depth to cover all possible objects. Draw each object to the secondary entirely in the "color" of it's object number. When you read through the mask and get a non-zero pixel the "color" is the object number you hit.
This resolves all possible collisions in O(n) time rather than the O(n^2) of calculating interactions.

Farseer Physics XNA Geom 'Tripping'

I have an issue similar to http://farseerphysics.codeplex.com/Thread/View.aspx?ThreadId=72364
I have a rectangle player geom, and many rectangle tile geoms lined up next to each other.
Occasionally when the player geom is crossing between them he seems to clip onto the corners of the tile geom and as a result rotate over.
Even when switching the moment of inertia to infinity which prevents rotation, the player geom "hops" when it clips the edge.
Here is a screenshot of the geoms tripping image http://notspike.com/PrototypeG/trip.png
Is there any fix for this? I've tried the Farseer forums but it seems pretty inactive
Here is a link to a video using a circle geom for the player
http://www.notspike.com/PrototypeG/trip.avi
I would suggest that you avoid the use of small tiles placed next to each other for the level's collision geometry. For example, although visually it's clear that you're using tiles, the "floor" from the video would best be described as a long contiguous rectangle. That way, you don't have this problem at all ... floating point math is already imprecise enough and tiling collision geometry is just asking for that to go wrong :-)
I've had this happen before when my shapes are small enough or the movements are fast enough for the interval between physics calculation "ticks" to be enough to allow the objects to overlap before the collision detection kicks in.

Resources