1
votes

I was trying to change the velocity of a Physics Body that is attached to a rectangle with the movement of the accelerometer. I cannot get the body to change velocity, is it a permanent property once it is set?

this is in my populateScene:

rect = new Rectangle(220, -200, 24, 24, this.getVertexBufferObjectManager());
rect.setColor(Color.GREEN);
mScene.attachChild(rect); 

ball = PhysicsFactory.createBoxBody(mPhysicsWorld, rect, BodyType.DynamicBody, droppingBoxDef);

mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
                    rect, ball));

and this is where I try to change the velocity:

@Override
    public void onAccelerationChanged(AccelerationData pAccelerationData) {

        int accellerometerSpeedX = (int)pAccelerationData.getX();
        //   accellerometerSpeedY = (int)pAccelerometerData.getY();
        //Log.v("Accelerometer X Y Z: ", ""+pAccelerationData);

        ball.setLinearVelocity(accellerometerSpeedX, 0);

    }

Without the second portion above the rectangle loads fine and has its physics body working correctly. It seems to disappear when I try to use: ball.setLinearVelocity.

The Body object is a global variable in the class so it can be referenced in both methods. I have tried using a update handler inside of Populatescene and setting ball.setLinearVelocity in there, however that gave the same results.

Essentially my question is: Can the velocity of a Body be changed after it has been connected to the physics world?

1
Do not mess with the physicsworld from another thread than the AndEngine UpdateThread! I cannot recall which system Thread the accelerometer callback is called from (UIThread, SensorThread??) but it's not the AndEngine UpdateThread and therefore you might get unexpected behavior or a crash if you don't dispatch that call to the UpdateThread.Nicolas Gramlich
So what should I do? Store the accelerometer change in a global variable and use that value within the AndEngine UpdateThread?Jaiesh_bhai
That or runOnUpdateThread.Nicolas Gramlich
Do you have any examples of how to do this? I am having trouble understand how and when to use certain updateHandlers. Thanks for your time and thanks a lot for AndEngine. Its great!Jaiesh_bhai

1 Answers

2
votes

Typicly in Box2D you do not setVelocities, but rather apply impulses or forces to a body to cause it to accelerate or decelerate.
For what you are describing above, you should not be using setLinearVelocity. Try using

ball.applyForce(new Vector2(accellerometerSpeedX, 0), ball.getWorldCenter());

or

 boxBody.applyAngularImpulse(new Vector2(accellerometerSpeedX, 0));