I have set the gravity of my world as follows
world=new b2World(b2Vec2(0.0,9.8));
I have a dynamic body called b2Body* sta1 which is falling from the top of the screen. And I have another dynamic body sta2 which should not fall i.e it just move on some keypress. The problem is how can I give this body of my world zero gravity i.e is there any way to give different gravity values to different bodies in the world?
yes you are right. You should set the gravity scale of the body defition.
sta2def.gravityScale = 0.0f;
Related
I am creating an app in which i am trying to Join two bodies in such away that when i move one body, the second body should be moved within the first body.
Here's my code to create a body:
- (b2Body *)addBoxBodyForDynamicSprite:(CCSprite *)sprite {
b2BodyDef spriteBodyDef;
spriteBodyDef.type = b2_dynamicBody;
//spriteBodyDef.position.Set(sprite.position.x/PTM_RATIO, sprite.position.y/PTM_RATIO);
CGPoint asolutePoint = [sprite.parent convertToWorldSpace:sprite.position];
spriteBodyDef.position.Set(asolutePoint.x/PTM_RATIO, asolutePoint.y/PTM_RATIO);
spriteBodyDef.userData = (__bridge void*)sprite;
b2Body *spriteBody = world->CreateBody(&spriteBodyDef);
b2PolygonShape spriteShape;
spriteShape.SetAsBox(sprite.contentSize.width/PTM_RATIO/2,
sprite.contentSize.height/PTM_RATIO/2);
b2FixtureDef spriteShapeDef;
spriteShapeDef.shape = &spriteShape;
spriteShapeDef.density = 0.3;
spriteShapeDef.isSensor = true;
spriteBody->CreateFixture(&spriteShapeDef);
return spriteBody;
}
One body is kinematic and other body is Dynamic. I am moving these bodies by using:
theBody->SetTransform(locationWorld, theBody->GetAngle());
If i apply linear force here, the bodies are not moving & the Joint which i used to fix them is b2WeldJoint.
b2JointDef jointDef;
jointDef.bodyA = another;
jointDef.bodyB = leftHandFixBody;
aJoint = (b2Joint *)world->CreateJoint(&jointDef);
It moves the dynamic body but the kinematic body remains on its position. I want to move both the bodies together. Any help will be really appreciated. Thanks!
Also, according to the manual, kinematic bodies are moved by setting their velocity, not by applying forces.
A kinematic body moves under simulation according to its velocity.
Kinematic bodies do not respond to forces. They can be moved manually
by the user, but normally a kinematic body is moved by setting its
velocity. A kinematic body behaves as if it has infinite mass,
however, Box2D stores zero for the mass and the inverse mass.
Kinematic bodies do not collide with other kinematic or static bodies.
Also, I have found that using SetTransform(...) to move bodies is less than effective. I created a portal with it to jump a body from one place to another, and that worked. But if I updated it every simulation cycle, the body stopped colliding with other bodies. This is just a word of caution.
Was this helpful?
i'm losing myself in this...
Situation:
Working on a game in cocos2d with box2d and I have a ropejoint between one fixed body and one dynamic body.
When I drop the dynamic body is swings from left to right and then from right to left due to the gravity in the world.
The problem:
The swings are getting shorter and shorter till finally the dynamic body hangs still beneath the fixed body. This is normal behavior but I need it to keep swinging.
My thoughts:
I think I need to apply a tangential force to the ropejoint in the direction of the swinging but how to do this is a mystery for now :)
Try setting the damping factor of the rope joint to zero
ropeJointDef.dampingRatio = 0.0f;
Hope it helps!
Here is a little code that should help you with your little problem
bool YourClass::init(){
CCCallFunc *swingL = CCCallFunc::create(this,callfunc_selector(YourClass::swingLeft));
CCDelayTime *delay = CCDelayTime::create(5);
CCCallFunc *swingR = CCCallFunc::create(this, callfunc_selector(YourClass::swingRight));
this->runAction(CCRepeatForever::create(CCSequence::create(swingL,delay,swingR,NULL)));
}
void YourClass::swingLeft(){
b2Body *dynamicBody = get your body from b2world;
dynamicBody->SetLinearVelocity(b2Vec2(-10, 0));//set velocity of the swing
}
void YourClass::swingRight(){
b2Body *dynamicBody = get your body from b2world;
dynamicBody->SetLinearVelocity(b2Vec2(10, 0));//set velocity of the swing
}
I haven't been able to find this after scavenging the forums. I would like to implement something like this ... the main character always moves in the direction it's facing. When the player touches the screen, the character will turn to face that touch location, which should cause the body to move in a different direction.
I can get the character to face a touch location as follows:
CGPoint diff = ccpSub(location, self.position);
CGFloat targetAngle = atan2f(diff.y, diff.x);
self.body->a = targetAngle;
I want something along these lines. Get the current angle the character is facing. Turn that angle into a unit vector. Multiply that unit vector by a max_velocity, and apply it to the character. This should should (theoretically) move the character in the direction it is facing at a constant velocity?
This seems to give me what I want:
cpVect rotatedVel = cpvmult(ccpForAngle(self.body->a), MAX_VELOCITY);
self.body->v = cpvlerpconst(self.body->v, rotatedVel, ACCELERATION * dt);
Now all I need is a way to rotate the character's direction slowly over time. How might I do that?
Sounds like you want to do something like this from Chipmunk's Tank demo:
// turn the control body based on the angle relative to the actual body
cpVect mouseDelta = cpvsub(ChipmunkDemoMouse, cpBodyGetPos(tankBody));
cpFloat turn = cpvtoangle(cpvunrotate(cpBodyGetRot(tankBody), mouseDelta));
cpBodySetAngle(tankControlBody, cpBodyGetAngle(tankBody) - turn);
'turn' is calculated relative to the body's current rotation by transforming the direction vector relative to the body's current rotation. The demo smooths out the rotation using constraints (which you might want to consider here too), but you could also just get away with using cpflerpconst() on 'turn' to get a maximum angular velocity too.
What about using the cpBodySetTorque to set object torque to make it spin/rotate?
I'm trying to make a system of "chunks" in Box2D - i.e. shapes that are attached together in a big lump, so that you can break chunks off into their own body.
Currently, my system is very basic (just starting really) and modelled after the "Breakable" test in the Box2D testbed. It's a body with quite a few basic box fixtures (which will later become polygons). When you click a body, it deletes the fixture and creates a new body with the same fixture, rotation, etc in the same place as the old "chunk".
However, I can only get it to create the new body at the big body's origin
(->GetWorldCenter). What I want to do is find the global location of the fixture to be deleted and replaced, so I can make the new chunk there.
I've read some stuff about b2PolygonShape having a "centroid", but I'm not sure how to access and use that...
To put it simply, I want to find the global location (as x+y or a b2Vec2) of a FIXTURE, NOT a body (that's easy). The fixture will move with the body it's attached to, but I only currently need the position for one frame (having it update would be useful too though).
For Box2D position of the body not so important. Body position is only shift for fixture coordinates. It do not impact to simulation process. So, I don't understand, why you so care about this.
I made something like this, and can say, that using big body's origin works fine. You can see into Box2D testbed to Breakable test. There also used big body's origin. Only reason to calculate new coordinates that I see is strange behavior of SetAngle method.
If you still want centroid, look at ComputeCentroid, located at b2PolygonShape.cpp. Pay attention, method don't declared at b2PolygonShape.h. You can copy code from cpp and use it like this:
b2Fixture* chunk = ...;
b2Vec2 chunkCentroidLocal = ComputeCentorid(chunk->m_vertices,
chunk->m_vertexCount);
b2Vec2 chunkCentroidWorld = bigBody->GetWorldPoint(chunkCentroidLocal);
p.s. Don't forget to transform polygon points, when you will create new body. Simply find difference between big body and new body, and subtract it from every point of polygon.
b2Vec2 shift = chunkCentroidWorld - bigBody->GetWorldCenter();
b2Vec2 newVertices = new b2Vec2[chunk->m_vertexCount];
for(int i = 0; i< chunk->m_vertexCount; i++)
{
newVertices[i] = chunk->m_vertices[i] - shift;
}
How can my sprite will jump and come back to original place??
I am using box2d physics engine in iphone apps.
I am using impulse but cant work properly.
Is any one know the logic or code than tell me.
-(void)jump
{
b2Vec2 pos=ballbody->GetPosition();
// float vel=ballbody->GetAngularVelocity();
double radian=atan2(pos.x+10, pos.y+10);
float angle=CC_RADIANS_TO_DEGREES(radian);
NSLog(#"Angle: %f",angle);
float impulseFactor = 1.0;
float force=ballbody->GetMass()*10;
//force/=6.0;
//b2Vec2 force=b2Vec2(0,50.0f);
// float apply=force*JUMP_IMPULSE*impulseFactor;
ballbody->ApplyLinearImpulse(b2Vec2(angle,force), ballbody->GetWorldCenter());
// [self applyLinearImpulse:b2Vec2(0,[self mass]*JUMP_IMPULSE*impulseFactor) point:[self worldCenter]];
}
Thanks
please check whether gravity has been set
if not set gravity upon the particular angle you have put the force.
third case is note down that position... get the current position... get angle.... set linear velocity to that angle.... keep on checking the position and as soon as it reaches that position set linear velocity zero..... (this sounds confusing but i didn't understood your problem fully so as much as i did understood i can help only this much)