Search code examples
androidandengineanglethrow

andengine throw a ball with a force and at a particular angle


In AndEngine game, I want to throw a ball physics body. The user sets its angle and force and throws it. Its scenario is same as we can see in Angry Birds. I have calculated both the force and angle but am confused how to apply both simultaneously on ball means the ball should be thrown at calculated angle but with particular force. Can anybody guide me to the right direction?

Here is my code snippet:

@Override
public boolean onAreaTouched(TouchEvent event,ITouchArea pTouchArea, float x, float y) {
    // TODO Auto-generated method stub
    if(event.isActionDown()) {
        ......
    }
    else if(event.isActionMove()) {
        ......
    }
    else if(event.isActionCancel() || event.isActionOutside() || event.isActionUp()) {
        .....
        launchHero(hero, string1.getX1()/PIXEL_TO_METER_RATIO_DEFAULT, string1.getY1()/PIXEL_TO_METER_RATIO_DEFAULT, x/PIXEL_TO_METER_RATIO_DEFAULT, y/PIXEL_TO_METER_RATIO_DEFAULT);
}

public void launchHero(Hero hero, float originX, float originY, float fingerX, float fingerY) {
    Vector2 shoot = new Vector2((originX - fingerX), -(originY - fingerY));
    shoot = shoot.nor().mul(10);

    hero.getBody().setLinearVelocity(shoot);

}
    }

    return false;

}

I have added negative to (originY - fingerY) because if I don't do this, the ball first goes down then after colliding with base, it goes up.


Solution

  • It's very simple, use Body.setLinearVelocity(Vector2 pVector). Both direction and force are determined by the vector's parameters. Here's a sample code:

    Vector2 shoot = new Vector2((originX - fingerX), (originY - fingerY));
    body.setLinearVelocity(shoot);
    

    This will shoot the body in the direction made by the finger and place of origin, or, in the case of Angry Birds, the finger and the sling.

    If you want to make the force constant and multiply it by some number, you can do this before shooting:

    shoot = shoot.nor().mul(multiplier);