androidlibgdxtouchdragtouchpad

Libgdx touch and drag anywhere onscreen to move sprite


Currently I am using the scene2d touchpad to move a sprite on screen. What I want to be able to do is to use all of the screen as a touchpad to move the sprite but have no idea where to start.

Basically its a touchpad without actually using the scene2d touchpad


Solution

  • Basically you got the answer in the comments.

    1. Use InputProcessor
    2. Save touch position on touch
    3. Check distance between the saved touch position and the current touch position on touch drag

    A little code as example:

    class MyInputProcessor extends InputAdapter
    {
        private Vector2 touchPos    = new Vector2();
        private Vector2 dragPos     = new Vector2();
        private float   radius      = 200f;
    
        @Override
        public boolean touchDown(
                int screenX,
                int screenY,
                int pointer,
                int button)
        {
            touchPos.set(screenX, Gdx.graphics.getHeight() - screenY);
    
            return true;
        }
    
        @Override
        public boolean touchDragged(int screenX, int screenY, int pointer)
        {
            dragPos.set(screenX, Gdx.graphics.getHeight() - screenY);
            float distance = touchPos.dst(dragPos);
    
            if (distance <= radius)
            {
                // gives you a 'natural' angle
                float angle =
                        MathUtils.atan2(
                                touchPos.x - dragPos.x, dragPos.y - touchPos.y)
                                * MathUtils.radiansToDegrees + 90;
                if (angle < 0)
                    angle += 360;
                // move according to distance and angle
            } else
            {
                // keep moving at constant speed
            }
            return true;
        }
    }
    

    And last you can always check the source of the libgdx classes and see how its done.