Search code examples
box2dandengineaccelerometergame-physics

Restricting movement of box2d body along an axis in andEngine


Purpose is to restrict the movement of a box2d physics body in a certain axis - to move either horizontally or vertically, Here is the body definition :

Body ballBody;
Sprite ball;    
ball = new AnimatedSprite(x_end, y_end-ballTextureRegion.getHeight(), this.ballTextureRegion, this.getVertexBufferObjectManager());
ballBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, ball, BodyType.DynamicBody, FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(ball, ballBody, true, true));
scene.registerUpdateHandler(this.mPhysicsWorld);
scene.attachChild(ball);

The ball moves in all directions by accelerometer using andEngines IAccelerationListener, What has been tried to restrict the body along x axis, so that it moves only vertically :

In the main game loop, have set x component of its linear velocity as 0 :

scene.registerUpdateHandler(new IUpdateHandler() {

    public void reset() {
    }

    // main game loop
    public void onUpdate(float pSecondsElapsed) {
        ballBody.setLinearVelocity(0, ballBody.getLinearVelocity().y); // set x velocity as 0
   }
});

But now also the ball can move horizontally, its horizontal speed is now lesser but not totally 0. How to restrict its movement along one direction only ?


Solution

  • I solved the problem by changing the type of box2d body from dynamic to kinematic, read about body types from here, and found that in my case kinematic body was better as a dynamic body it was getting affected by all the forces in physical world.

    ballBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, ball, BodyType.KinematicBody, FIXTURE_DEF);
    

    And set its velocity along y axis like this for vertical movement:

    penBody.setLinearVelocity(mPhysicsWorld.getGravity().x, 0);