1

I'm using AndEngine and Box2d to develop a game. I'm applying a force to a body to keep it "aloft" equal to that of gravity. I have the scene set up so that:

public void onAccelerationChanged(final AccelerationData pAccelerationData) {
        gravity = Vector2Pool.obtain(pAccelerationData.getX(), pAccelerationData.getY());
        this.mPhysicsWorld.setGravity(gravity);
        Vector2Pool.recycle(gravity);
    }

Now I need to set my force applied:

body.applyForce(new Vector2(0,-*gravity*), new Vector2(body.getWorldCenter()));

How do I get the value of the gravity so that I can apply it as a force when the screen is tilted?

rphello101
  • 1,671
  • 5
  • 31
  • 59

2 Answers2

1

If you are trying to have an object which isn't affected by gravity, you can set its body as static or kinetic. It is more efficient and avoids you extra processing.

BTW, I guess you are getting null because you have already recycled the vector with this line

Vector2Pool.recycle(gravity);

Edit:

Why you don't simply use something like this?

public void onAccelerationChanged(final AccelerationData pAccelerationData) {
    gravity = Vector2Pool.obtain(pAccelerationData.getX(), pAccelerationData.getY());
    this.mPhysicsWorld.setGravity(gravity);
    body.applyForce(new Vector2(-pAccelerationData.getX(), -pAccelerationData.getY()), new Vector2(body.getWorldCenter()));
    Vector2Pool.recycle(gravity);
}
gian1200
  • 3,670
  • 2
  • 30
  • 59
  • True, however, I cannot set it to static or kinetic. I need to apply a force to it and it has to collide with other bodies. For that reason, I have to apply "anti-gravity." I surmised that is why I had a NPE as well; however, deleting it still caused a problem because I wasn't able to access the value correctly. My question is, how do I get the value of the gravity so that I can apply it as a force when the screen is tilted? – rphello101 Jul 01 '12 at 07:52
  • That worked, kinda. Stored pAccelerationData.getX() and .getY() to two separate floats and applied the force in an update handler, but essentially the same. – rphello101 Jul 02 '12 at 08:42
0

I made some alterations to the Box2D extension to include the setGravityScale method from the more recent version of Box2D. I posted the link at,

how-do-i-make-a-body-ignore-gravity-andengine

e.g., to make a body ignore gravity call,

Body.setGravityScale(0.0f);

Where Body could be dynamic in your case. The point is you would not need to apply a force for every object which you need to defy gravity. The code which does this in the example was taken from Box2D 2.2.1.

I included an explanation of how it was implemented. There is also a download provided for GLES1.

Hope this helps.

Community
  • 1
  • 1
Steven
  • 798
  • 7
  • 14