Applying gravity to the physics world is easy, you just need to create a Vector2
and set its horizontal and vertical gravity value. What if I want to create a top-down 2D game with zero gravity, and only apply gravity to specific body like a projectile motion of an arrow. Of course it's easy to have an projectile motion if you set your world to have a gravity at first.
float GRAVITY_EARTH = -9.8f;
Vector2 gravity = new Vector2(0, GRAVITY_EARTH);
World world = new World(gravity, true);
Box2d body class has a method that cancel or reverse the gravity, but I don't want to use it every time, just like in the below code example.
body.setGravityScale(0); // set 0 to cancel the gravity, and set -1 to reverse the gravity
But I want to be versatile, I want to apply gravity to specific body only. For example I'm using the method setLinearVelocity
to move the body to specific destination. Now if the world has the gravity y of -9.8f it will automatically have a projectile motion.
Vector2 initialVelocity = targetPoint.sub(originPoint).nor();
initialVelocity.scl(speed); // to apply constant speed
body.setLinearVelocity(initialVelocity);
I tried increment the initial velocity of y to -9.8 to apply gravity. But it didnt work, what am I missing?
initialVelocity.y += -9.8f;
body.setLinearVelocity(initialVelocity);
// or
body.applyForce(initialVelocity, body.getWorldCenter(), true);