6

I am currently learning libgdx game programming,now i have learnt how to use touchDown but iam not getting idea how to use touchDragged.How will the computer knows in which direction the finger is dragged(whether the user has dragged to left or right)

Turkhan Badalov
  • 845
  • 1
  • 11
  • 17
suvimsgowda
  • 97
  • 1
  • 4

2 Answers2

13

The computer doesn't know that. Or at least the interface won't tell you this information. It looks like this:

public boolean touchDragged(int screenX, int screenY, int pointer);

It is nearly the same like touchDown:

public boolean touchDown(int screenX, int screenY, int pointer, int button);

After a touchDown event happened, only touchDragged events will occur (for the same pointer) until a touchUp event gets fired. If you want to know the direction in which the pointer moved, you have to calculate it yourself by computing the delta (difference) between the last touchpoint and the current one. That might look like this:

private Vector2 lastTouch = new Vector2();

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    lastTouch.set(screenX, screenY);
}

public boolean touchDragged(int screenX, int screenY, int pointer) {
    Vector2 newTouch = new Vector2(screenX, screenY);
    // delta will now hold the difference between the last and the current touch positions
    // delta.x > 0 means the touch moved to the right, delta.x < 0 means a move to the left
    Vector2 delta = newTouch.cpy().sub(lastTouch);
    lastTouch = newTouch;
}
noone
  • 19,520
  • 5
  • 61
  • 76
0

The touch dragged method is called every frame that the touch position changes. The touch down method is called every time you touch the screen down, and touch up when you release.

LibGDX - Get Swipe Up or swipe right etc.?

This can help you a little bit.

Community
  • 1
  • 1
Boldijar Paul
  • 5,405
  • 9
  • 46
  • 94