Question

I have two bodies(A,B). I want B follows A. I can change B position with setTransfrom() function to A position. But I have to change B's position in every frame rate. So I have to use something like contact listener. When I use normal object in Andengine, it has this function below instead of contactlistener.

this.foot = new Rectangle(this.getX(), this.getY(), 8, 10, ResourcesManager.getInstance().vbom){
        @Override
        protected void onManagedUpdate(float pSecondsElapsed)
        {
           // super.onManagedUpdate(pSecondsElapsed);

            this.setPosition(body.getPosition().x*PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT+1,
                    body.getPosition().y*PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT-15);

        }
    }; 

I mean I can set this kind of listener when I am creating it.Is there any option for box2d body? I mean something like that:

this.footBody=PhysicsFactory.createBoxBody(this.mPhysicsWorld, this.foot, BodyType.DynamicBody, footFixtureDef){
        @Override
        protected void onManagedUpdate(float pSecondsElapsed)
        {
           // super.onManagedUpdate(pSecondsElapsed);

            this.setPosition(body.getPosition().x*PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT+1,
                    body.getPosition().y*PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT-15);

        }
    };
Was it helpful?

Solution

The poisition updates of physics bodies is managed by the Box2D library. But you can register an additional update handler to your scene and tell the box2D world what you want done during that update.

this.scene.registerUpdateHandler(new IUpdateHandler() {
@Override
public void onUpdate(float pSecondsElapsed) {
        // TODO Auto-generated method stub
        //Your code to run here!
}

So if you maintain a list of references to the bodies in your world, you should be able to apply forces or set their positions on each tick of the game. If you want to make sure you update the world before or after the box2D world step, you could event call

mBox2dWorld.onUpdate(pSecondsElapsed);

from within your own update handler, instead of registering the world as an updateHandler itself.

Here are a couple of less practical suggestions as well: Or to do that the box2D way you could use a joint. I depends on the following behavior you want.

OR... you don't even have object B as part of the Box2D world, perhaps, and just manage the following behavior outside of box2D. Does it need to collide with stuff?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top