Kostya  Khuta
Kostya Khuta

Reputation: 683

How to make physics in Andengine

i have a sprite, that must always go down, but when i tap the screen it must go up, somthink like Flappy Bird. I try next

  scene.registerUpdateHandler(detect);
    IUpdateHandler detect = new IUpdateHandler() {
    @Override
    public void reset() {
    }

    @Override
    public void onUpdate(float pSecondsElapsed) {
        MoveYModifier mod2=new MoveYModifier(0.8f,plSprite.getY(),plSprite.getY()+10);
        plSprite.registerEntityModifier(mod2);
    }
};

and code when i type screen

  @Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
    Log.d("myLogs","touch");
    MoveYModifier mod2=new MoveYModifier(0.1f,plSprite.getY(),plSprite.getY()-40);
            plSprite.registerEntityModifier(mod2);
    return false;  //To change body of implemented methods use File | Settings | File Templates.
}

But it does not work, problem is in next. Sprite is only go down.

Upvotes: 1

Views: 561

Answers (1)

Mateusz Gaweł
Mateusz Gaweł

Reputation: 683

Let's say you have flying pig game similiar to Flappy Bird. First, you have to create a sprite like this: (x position, y position, texture region, vertex buffer object manager)

Then you attach a physical body. You have to give your physics world, sprite, type of body (you will be interested in KinematicBody) and fixture definition which are 3 physical attributes.

Remember to attach sprite and register body to your physical world.

And finally you should register onTouch listener to your scene when you can use last method i mentioned. It will apply a force to the body. Notice that to jump you need to pass negative float parameter. Thanks to your physics world all kinematic bodies will fall down if you specify gravitation force.

Sprite sPig = new Sprite(0, 155, ResourcesManager.getInstance().pig_region, vbom);
pigBody = PhysicsFactory.createBoxBody(physicsWorld, sPig, BodyType.KinematicBody, PhysicsFactory.createFixtureDef(10.0f, 0, 0));

physicsWorld.registerPhysicsConnector(new PhysicsConnector(sPig, pigBody, true, false) {
    @Override
    public void onUpdate(float pSecondsElapsed) {
      super.onUpdate(pSecondsElapsed);
      //you can do some stuff here if you want.
    });
attachChild(sPig);

//in onSceneTouchListener
pigBody.setLinearVelocity(0, -30);

//this is how i create physics world. 100f is y (down) gravitation force.
physicsWorld = new FixedStepPhysicsWorld(60, new Vector2(0, 100.0f), false);
registerUpdateHandler(physicsWorld);

PS you will need Box2D extension included. I recommend you to see some tutorials.

Upvotes: 1

Related Questions