Box2d dynamic bullet body sinking into static bodies - cocos2d-iphone

I'm making a game in cocos2d with box2d and I'm running into some issues.
I have the program iterate through a tilemap's (.tmx) rows and columns , searching for tiles with a "collidable" property set to "true". If one is found, a square static box2d body (with fixtures and all) is set at that tile's position. So essentially, I should end up with a bunch of square bodies set up where I need them (depending on the tilemap) after the iteration is complete. I also have a square dynamic body that is controlled by gesture (up gesture slides it upward, down gesture downward, etc.), and it is supposed to only move in one of four directions: up, down, left, right. The restitution of the body is 0.0f so that it stops on impact with no rebound, and the friction is 0.0f as well because it's not needed (gravity of the world is 0.0f, 0.0f too). Since the iteration through the tilemap can only place bodies that are square, the "walls" in the game are composed of several of these squares lined up adjacent to each other, end to end, which creates a flush edge for the dynamic body to collide with.
The problem arises when the dynamic body collides with the wall of squares. I control movement of the body by setting the velocity of the body according to the gesture. An example of movement to the right would be:
#define bodyVel 100
...
if (gestureRight)
{
body->SetLinearVelocity( b2Vec2(bodyVel / PTM_RATIO, 0) );
}
I have the body set as a bullet so that when it collides with the wall it will not become embedded, but I have encountered some weird results. An example would be this:
I move the body rightwards into a wall and it stops. Good. Next, I want to move it up, so I gesture upwards. Good. But then, at times, as it is sliding up the wall, the body seems to "catch" on to something and it spins out of control and in multiple directions. Bad.
The only explanation I can come up with is that the dynamic body is in fact becoming imbedded in the wall upon the first head on contact, and as it slides up the wall upon the next given gesture for movement, it gets caught on the one of edges of the squares that make up the wall and becomes jarred from a straight path. I confirmed this strange activity by setting the body to have a fixed rotation (not rotate at all), and consequently, instead of the body spinning out of control, it would simply stop. This was expected given my hypothesis. So the dynamic body is becoming embedded is what I'm trying to say.
I don't understand why this is happening because I have the body set to behave like a bullet to avoid problems exactly like this. All I want the object to do is be able to move along a straight path - either up, down, left, or right -, stop upon contact with a wall, and move along the wall without interference from the bodies that make up the wall.
I feel like unless I have a misunderstanding of how bullet bodies work, the embedding that is occurring should not be an issue.
I also used to DebugDraw to see if the square static bodies created a flush wall and they did.

Unfortunately, this is a known issue in Box2d... from the FAQ:
Tile Based Environment
Using many boxes for your terrain may not work well because box-like
characters can get snagged on internal corners. A future update to
Box2D should allow for smooth motion over edge chains. In general you
should avoid using a rectangular character because collision
tolerances will still lead to undesirable snagging.
For more information see this post:
http://box2d.org/forum/viewtopic.php?f=3&t=3048

Related

Collision resolution issues with circles

I have a small application I have built where there are a few balls on a blank background. They all start flying through the air and use the physics I wrote to bounce accurately and have realistic collision responses. I am satisfied with how it looks except I have an issue where when my balls land directly on top of each other, the attach together and float directly up.
Here are the functions involved
https://gist.github.com/anonymous/899d6fb255a85d8f2102
Basically if the Collision function returns true, I use the ResolveCollision to change their velocities accordingly.
I believe the issue is from the slight re-positioning I do in ResolveCollision(). If they collide I bring them a frame or so backwards in location so that they are not intersecting still the next frame. However, when they are directly on top they bounce off eachother at such small bounces that eventually stepping back a frame isn't enough to unhook them.
I'm unsure if this is the problem and if it is, then what to do about it.
Any help would be awesome!
The trick is to ignore the collision if the circles are moving away from each other. This works so long as your timestep is small enough relative to their velocities (i.e. the circles can't pass through each other in a single frame).
When the circles first collide, you will adjust their velocity vectors so their relative velocity vector pushes them apart (because a collision will do that). After that, any further collisions are spurious because the circles will be moving apart, and will eventually separate completely. So, just ignore collisions between objects that are moving apart, and you should be fine.
(I've implemented such an algorithm in a 3D screensaver I wrote, but the algorithm is entirely dimension-agnostic and so would work fine for 2D circles).

Avoid ground collision with Bullet

I'm trying to use Bullet physic engine to create a 3D world.
I've got my character with a Capsule shape on his body and my ground his made of some static blocs stick together, here is a schema to illustrate my words:
The problem is present when my character run from one block to another: Bullet detect a collision and my character start to jump a little bit on y-axis.
How can I avoid the problem?
What I did to overcome this issue is the following:
Instead of have the capsule slide on the ground, I had a dynamic capsule ride on top of a spring.
I implemented the spring as several ray casts originating from bottom of the capsule.
The length of the spring was like half a meter or less and it would pull and push the capsule to and from the ground.
The grip/pull is important so the character wouldn't jump unexpectedly.
The springs stiffness controls how much bobbing you have.
This had the following effects
No unwanted collision with edge of geometry on the floor, since the capsule floats
Walking up stairs and slopes implemented implicitly. The spring would just "step" onto the stair's step and push the character capsule up.
Implementation of jumping was just matter of releasing the grip on the ground the spring had and giving the body an impulse.
A landing character after a jump or fall automatically displayed "knee-bending" as you would expect
Pleasant smoothing of vertical movements in general. Like on elevator platforms etc.
Due to the grip/pull to the ground, even when running downhill the character would not start to "fly" as you experience in some games (I find that annoying typically).
Ducking character = decrease the length of the spring and/or the capsule.
Sliding downhill? You can fully control it by checking the angles of the floor area the ray cast of the spring hit.
I had to play around a lot with the stiffness of the spring, the length of the spring, the length of the grip etc. but in the end I was very happy about how simple yet well this worked.
Your problem caller "Internal Edge Collision". I just found the solution few our hour ago.
If you are using btHeightfieldTerrainShapefor your world then you must use btBvhTriangleMeshShape to slove this problem.
Here is the answer.
Add this callback:
static bool CustomMaterialCombinerCallback(btManifoldPoint& cp,const btCollisionObject* colObj0,int partId0,int index0,const btCollisionObject* colObj1,int partId1,int index1)
{
btAdjustInternalEdgeContacts(cp,colObj1,colObj0, partId1,index1);
return true;
}
extern ContactAddedCallback gContactAddedCallback;
Afterwards create the btBvhTriangleMeshShape and add this code where pGround is your btBvhTriangleMeshShape:
// Enable custom material callback
pGround->setCollisionFlags(pGround->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(pGroundShape, triangleInfoMap);
Or you can open the InternalEdgeDemo example in Bullet to see how to implement it in detail.

Rotation and Movement with rigid body in Bullet Physics

I have made a rigid body for the player and have been trying to get the rigid body moving along with the player's controls.
What I mean is that whenever I press forward I want the rigid body to move forward in the direction the player is facing, same with back, left, right. So far I'm able to use apply force to move the rigid body in static directions.
My straight question is how do I move the player's rigid body in the direction the player is facing.
Other Details:
I don't really want to use kinematic bodies if not necessary mostly because their very fiddly at the moment
I'm using glfw3 for input
This is quite amazing that you would not see how to do that after you actually managed to apply forces in static directions to something you configured over bullet.
Come on, you HAVE the skill to figure it out.
Here, just a push in the direction (hehe), hem. Just take the vector of the facing direction (which could be determined by camera, 1st or 3rd view, or even something else...).
Congrats, this vector is your force by a k factor.
You should also modulate this force according to speed, you don't need to accelerate to infinite speed, just accelerate lots at first and then regulate force to tend to desired walk speed.
Then, the side directions are obtained by rotating the facing vector by 90 degrees around the standing axis (most surely the vertical). You can obtain that by simply swapping components and multiplying by -1 one of them. x,y,z becomes y,-x,z
To go backward, its just -x, -y, -z on the facing vector.
So your up key is not bound to 0,1,0 but to facing_dir actually. This facing dir can change with mouse or some other view controls, like numeric keys 2,6,8,4 for example. Or you could drop up,left,right,down for movement and use w,a,s,d like everybody else, and use direction keys to rotate facing direction. (+mouse)
It is much more difficult to obtain the facing vector from mouse movement or direction keys than finding out how to apply the force, so if you already have the facing vector I'm puzzled that you even have a problem.

Keeping Velocity Constant and Player in Position - Sidescrolling

I'm working on a Little Mobile Game with Cocos2D-X and Box2D.
The Point where I got stuck is the movement of a box2d-body (the main actor) and the according Sprite. Now I want to :
move this Body with a constant velocity along the x-axis, no matter if it's rolling (it's a circleshape) upwards or downwards
keep the body nearly sticking to the ground on which it's rolling
keep the Body and the according Sprite in the Center of the Screen.
What I tried :
in the update()- method I used body->SetLinearVelocity(b2Vec2(x,y)) to higher/lower values, if the Body was passing a constant value for his velocity
I used to set very high y-Values in body->SetLinearVelocity(b2Vec2(x,y))
First tried to use CCFollow with my playerSprite, which was also Scrolling along the y-axis, as i only need to scroll along the x-axis, so I decided to move the whole layer which is containing the ambience (platforms etc.) to the left of my Screen and my Player Body & Player sprite to the right of the Screen, adjusting the speed values to Keep the Player in the Center of the Screen.
Well...
...didn't work as i wanted it to, because each time i set the velocity manually (I also tried to use body->applyLinearImpulse(...) when the Body is moving upwards just as playing around with the value of velocityIterations in world->Step(...)) there's a small delay, which pushes the player Body more or less further of the Center of the Screen.
... didn't also work as I expected it to, because I needed to adjust the x-Values, when the Body was moving upwards to Keep it not getting slowed down, this made my Body even less sticky to the ground....
... CCFollow did a good Job, except that I didn't want to scroll along the y-axis also and it Forces the overgiven sprite to start in the Center of the Screen. Moving the whole Layer even brought no good results, I have tried a Long time to adjust values of the movement Speed of the layer and the Body to Keep it negating each other, that the player stays nearly in the Center of the Screen....
So my question is :
Does anyone of you have any Kind of new Approach for me to solve this cohesive bunch of Problems ?
Cheers,
Seb
To make it easy to control the body, the main figure to which the force is applied should be round. This should be done because of the processing mechanism of collisions. More details in this article: Why does the character get stuck?.
For processing collisions with the present contour of the body you can use the additional fixtures and sensors with an id or using category and mask bits. For of constant velocity is often better to use SetLinearVelocity, because even when using impulse velocity gets lost at sharp uphill or when jumping. If you want to use the implulse to change the position of the body, then you need to use the code for the type of this:
b2Vec2 vel = m_pB2Body->GetLinearVelocity();
float desiredVel = mMoveSpeed.x; //set there your speed x value
float velChange = desiredVel - vel.x;
float impulse = m_pB2Body->GetMass() * velChange;
m_pB2Body->ApplyLinearImpulse( b2Vec2(impulse, mMoveSpeed.y), m_pB2Body->GetWorldCenter());
This will allow maintain a constant speed most of the time. Do not forget that these functions must be called every time in your game loop. You can combine these forces, depending on the situation. For example, if the at the beginning you need to make a small acceleration, it is possible to use ApplyForce to the body, and when a desired speed is to use ApplyLinearImpulse or SetLinearVelocity. How correctly to use it is described here: Moving at constant speed
If you use world with the normal gravity(b2Vec2(0, -9.81)), then it should not be a problem.
I answer for this question here: Cocos2D-x - Issues when with using CCFollow. I use this code, it may be useful to you:
CCPoint position = ccpClamp(playerPosition, mLeftBounds, mRightBounds);
CCPoint diff = ccpSub(mWorldScrollBound, mGameNode->convertToWorldSpace(position));
CCPoint newGameNodePosition = ccpAdd(mGameNode->getPosition(), mGameNode->getParent()->convertToNodeSpace(diff));
mGameNode->setPosition(newGameNodePosition);
P.S. If you are new to box2d, it is advisable to read all the articles iforce2d(tuts), they are among the best in the network, as well as his Box2D Editor - RUBE. At one time they really helped me.
I do not know if this is possible but I have an idea:
Keep the circle at a fixed position and move the background relatively. For example, during the course of the game, if the circle has a velocity of 5 towards left then keep circle fixed and move screen with velocity 5 towards right. If circle has 5 velocity towards left and screen has 3 velocity towards right, then keep circle fixed and move screen with 8 velocity towards left and so on. This should allow you to fix the circle at the center of the screen.
Another method would be to translate the entire screen along with the ball. Make everything on the screen an object that can have a velocity. And the x-component of the velocity of the ball (circle) should be the velocity of all other objects. This way, whenever the circle moves, all the other objects will try and keep up with it.

How to make a moving object "stick" to a stationary object in box2D

I have been experimenting with the box2D sample project within cocos2D for the iPhone and am wondering if box2D is the appropriate engine to use to make a moving object "stick" to a stationary object when the moving object is finished moving in a certain direction.
Here is a simplification of what I am trying to achieve: I have MovingObject, a dynamic rigid body, that moves vertically against gravity when enough force is applied to it. As MovingObject moves, it may overlap a static object, StationaryObject. When gravity diminishes MovingObject's velocity to zero such that it is no longer moving, I would like to have MovingObject remain where it is ONLY if it overlaps StationaryObject. If the object's do not overlap, MovingObject should start to move back down towards the ground per the force of gravity. During that descent, if MovingObject at any time overlaps StationaryObject, it should stop its descent and remain in that location as if it is stuck on StationaryObject.
I am able to get MovingObject to move per the forces I am applying to it, but not really sure how to make it stop and stay there once it reaches the top of its ascent, assuming it is overlapping StationaryObject.
Currently, I am experimenting with simple square/box objects but eventually both MovingObject StationaryObject will be defined as very different complex polygon shapes.
Thanks in advance for any insights and/or suggestions for achieving this.
Sounds like you'll want to change the type of fixture used for "MovingObject" while it "ascending" and then change it when it is "descending" so that it reacts differently (to overlaps).
by "overlap" it sounds like you want to achieve something similar to "one sided platforms" in a platform game (ie; Mario Bros.) - I would recommend looking into the solutions for one-sided platforms for starters.