Search code examples
touchandenginespritearea

Make Sprite Draggable When Touched


Is there a way to make a sprite draggable but only when the sprite itself is touched? Currently i have my game ,which uses anengine, set up to where the sprite follows your finger ever time the scene is touched. If you touch the opposite side of the scene the sprite gets "teleported" which is what i dont want.

I tried overriding the onAreaTouched method of the sprite and made it set its coordinates to where your finger currently is but this doesnt work too well. If you make sudden movements the draggablity wears off.

is there any simple way to accomplish this?


Solution

  • Answering my own question... i used this code and it worked perfectly:

            draggableSprite = new Sprite(CAM_WIDTH/2, CAM_HEIGHT/2, 
            spriteTextureRegion, mVertexBufferObjectManager){
    
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float pTouchAreaLocalX, float pTouchAreaLocalY) {
    
                    if(pSceneTouchEvent.isActionMove()){
                        spriteIsTouched = true;
                    }
                    else{
                        spriteIsTouched = false;
                    }
                return super
                        .onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
            }
    
        };
        scene.attachChild(draggableSprite);
        scene.registerTouchArea(draggableSprite);
    
        scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
    
            @Override
            public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
                // TODO Auto-generated method stub
    
                if(spriteIsTouched){
                    draggableSprite.setPosition(pSceneTouchEvent.getX() - (draggableSprite.getWidth()/2), pSceneTouchEvent.getY() - (draggableSprite.getHeight()/2)); 
                    //This sets the position of the sprite and then
                    //offsets the sprite so its center is at your finger
                }
    
    
                return false;
            }
        });`