Search code examples
android2dandenginespritegame-physics

AndEngine: animated sprite not working with physics handler


Animated sprite not performing animation with a physics handler:

I'm using AnalogOnScreenControl of the AndEngine GLES2 to move a sprite. The sprite is a person and so to show leg movement I've made it an animated sprite:

final AnimatedSprite person = new AnimatedSprite(personX, personY,
            this.mPersonTextureRegion, vertexBufferObjectManager);
    person.setScaleCenterY(this.mPersonTextureRegion.getHeight());
    person.setScale(2);

For movement I'm creating a physics handler:

final PhysicsHandler physicsHandler = new PhysicsHandler(person);
person.registerUpdateHandler(physicsHandler);
scene.attachChild(person);

and this is the code of the screen control:

    final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(
            0, CAMERA_HEIGHT
                    - this.mOnScreenControlBaseTextureRegion.getHeight(),
            this.mCamera, this.mOnScreenControlBaseTextureRegion,
            this.mOnScreenControlKnobTextureRegion, 0.1f, 200,
            this.getVertexBufferObjectManager(),
            new IAnalogOnScreenControlListener() {
                @Override
                public void onControlChange(
                        final BaseOnScreenControl pBaseOnScreenControl,
                        final float pValueX, final float pValueY) {
                     physicsHandler
                     .setVelocity(pValueX * 100, pValueY * 100);
                     person.animate(new long[] { 200, 200, 200 }, 3, 5,
                     false);

                }

The screen control works flawlessly for the animated sprite but when I create the physics handler it doesn't animate. But it animates when I don't create a physics handler. So why doesn't it animate when I create a physics handler?


Solution

  • Figured it out! Animation must started only if pValueX isn't 0, i.e., if sprite is moving.

    public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
    if (pValueX > 0) {
    //animate
    }
    
    else
    //stop animation
    
     physicsHandler.setVelocity(pValueX * 100, pValueY * 100);
    }