Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does touchDragged work in libgdx?

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)

like image 589
suvimsgowda Avatar asked May 19 '14 06:05

suvimsgowda


1 Answers

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;
}
like image 158
noone Avatar answered Nov 06 '22 14:11

noone