开发者

Move object into screen without gravity into box2d in iPhone

开发者 https://www.devze.com 2023-02-16 15:04 出处:网络
i use following code to move my Box2D object into screen, but because gravity of my world or something else i dont know why my objects is forced to move down, i am new to box2d.

i use following code to move my Box2D object into screen, but because gravity of my world or something else i dont know why my objects is forced to move down, i am new to box2d.

i want to move my object in entire world without gravity.

-(void) tick:(NSTimer *)timer {

    int32 velocityIterations = 8;
    int32 positionIterations = 1;
    world->Step(1.0f/60.0f, velocityIterations, positionIterations);

    for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
    {
        if (b->GetUserData() != NULL)
        {
            UIView *oneView = (UIView *)b->GetUserData();
            CGPoint newCenter = CGPointMake(b->GetPosition().x * PTM_RATIO,self.view.bounds.size.height - b->GetPosition().y * PTM_RATIO);
            oneView.center = newCenter;
            CGAffineTransform transform = CGAffineTransformMakeRotation(- b->GetAngle());
            oneVie开发者_运维百科w.transform = transform;
        }
    }
}

my accelerometer code is as follow.

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    b2Vec2 gravity;
    gravity.Set( acceleration.x * 1.81,  acceleration.y * 1.81 );
    world->SetGravity(gravity);
}

pleas if any one work around.

Thanks.


As i understand you want to move your object setting it's position. It's a bad idea because it will provide non-physical behavior of the bodies colliding with your object. That's because if you will only change the position of your body it's velocity for physics engine will be still zero and collision will be processed according to zero speed of your object.

A better solution is to use b2_kinematicBody type for your object. Then you will be able to control it's motion specifying it's velocity vector and physics will behave as expected. Also the gravity (and no other forces) will not be applied to your object because of it's type.

EDIT

//creation
b2BodyDef bDef;
bDef.type = b2_kinematicBody;
bDef.position.Set(5, 6);

b2Body *body  = physWorld->CreateBody(&bDef);


//control
body->SetLinearVelocity(b2Vec2(3, 4));
0

精彩评论

暂无评论...
验证码 换一张
取 消