Reputation: 1814
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?
Upvotes: 1
Views: 1315
Reputation: 12527
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));
Upvotes: 2