3

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.

  • If the screen is just touched the sprite should not move.
  • The sprite should move at different speeds based on how far user has moved their finger from the initial touch point.
  • Once the user have dragged their finger outside a certain radius the sprite will continue to move at a constant speed.

Basically its a touchpad without actually using the scene2d touchpad

Steve Fitzsimons
  • 3,754
  • 7
  • 27
  • 66
  • You will have to implement your own custom `InputProcessor` to do this. Maybe a `GestureDetector` could help here, but in total there's nothing in libgdx that does this. I doubt somebody is going to code this for you. – noone Oct 24 '15 at 18:42
  • Was not suggesting someone code this for me I am just looking suggestions on where to start or pointers from anyone who may have attempted this before – Steve Fitzsimons Oct 24 '15 at 20:07

1 Answers1

4

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.

Pinkie Swirl
  • 2,375
  • 1
  • 20
  • 25