AndEngine - scroll sprites up and down

2019-05-21 10:20发布

问题:

I am a beginner andengine user and I need your help.

I have created a class MySprite extending sprite and I want the sprite to move up and down on the y - coordinate when I slide with the finger on the Screen by touching only the sprite.

I have tried to achieve this by implementing IScrollDetectorListener and IonSceneTouchListener but the Problem is: I can touch anywhere and my sprites moves.

I would be glad if someone could help.

For more Details just comment :)

回答1:

         Sprite mySprite = new Sprite(x, y, textureRegion, this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {

 this.setPosition(x, y);
            //Insert Code Here
            return true;
             }};

        // dont forgot to register your touch area i.e 
        mScene.registerTouchArea(mySprite);
    // Hoping it may help you.


回答2:

Hope you are trying to make a scroll bar kind off movement with sprite. Please use this code

Initial scrollbarPosition = scrollbar.getX(); //fix this position

final Sprite scrollbar= new Sprite(centerX, centerY, this.scrollbarTextureRegion, this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
                this.setPosition(scrollbarPosition, pSceneTouchEvent.getY() - this.getHeight() / 2);
                return true;
            }
        };

scene.attachChild(scrollbar);
scene.registerTouchArea(scrollbar);
scene.setTouchAreaBindingOnActionDownEnabled(true);

Hope this helps thanks.



回答3:

If you want to move it only on Y coordinate you first have to override onAreaTouched and then handle the Y movement while supressing the X movement. Try the following code:

Sprite mSprite = new Sprite(mX, mY, mTexture, this.mEngine.getVertexBufferObjectManager()) {                        
                    @Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
                        this.setPosition(this.getX(), pSceneTouchEvent.getY());                         
                        return true;
                    }
                };
                this.mScene.attachChild(mSprite);
                this.mScene.registerTouchArea(mSprite);

Oh, it will work fine if you are using GLES2-AnchorCenter branch!

Hope it helps! :)