Android libgdx swipe left and right detection using gesture listener

后端 未结 2 1241
再見小時候
再見小時候 2020-12-17 03:04

I have displayed a image at the center of the screen with libgdx. If i swipe left the image should move left and if i swipe right image should move right.

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 03:08

        public class Test extends Activity{
    
    private GestureDetector gesturedetector = null;
    
    View layout;
    
    @Override
    
    public void onCreate(Bundle savedInstanceState) {
    
    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.test);
    
    layout = (LinearLayout)findViewById(R.id.container);
    
    gesturedetector = new GestureDetector(new MyGestureListener());
    
    layout.setOnTouchListener(new OnTouchListener() {
    
    @Override
    
    public boolean onTouch(View v, MotionEvent event) {
    
    gesturedetector.onTouchEvent(event);
    
    return true;
    
    }
    
    });
    
    }
    
    public boolean dispatchTouchEvent(MotionEvent ev){
    
    super.dispatchTouchEvent(ev);
    
    return gesturedetector.onTouchEvent(ev);
    
    }
    
    class MyGestureListener extends GestureDetector.SimpleOnGestureListener{
    
    private static final int SWIPE_MIN_DISTANCE = 150;
    
    private static final int SWIPE_MAX_OFF_PATH = 100;
    
    private static final int SWIPE_THRESHOLD_VELOCITY = 100;
    
    @Override
    
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    
    float velocityY) {
    
    float dX = e2.getX()-e1.getX();
    
    float dY = e1.getY()-e2.getY();
    
    if (Math.abs(dY)=SWIPE_THRESHOLD_VELOCITY &&
    
    Math.abs(dX)>=SWIPE_MIN_DISTANCE ) {
    
    if (dX>0) {
    
    Toast.makeText(getApplicationContext(), “Right Swipe”, Toast.LENGTH_SHORT).show();
    
    } else {
    
    Toast.makeText(getApplicationContext(), “Left Swipe”, Toast.LENGTH_SHORT).show();
    
    }
    
    return true;
    
    } else if (Math.abs(dX)=SWIPE_THRESHOLD_VELOCITY &&
    
    Math.abs(dY)>=SWIPE_MIN_DISTANCE ) {
    
    if (dY>0) {
    
    Toast.makeText(getApplicationContext(), “Up Swipe”, Toast.LENGTH_SHORT).show();
    
    } else {
    
    Toast.makeText(getApplicationContext(), “Down Swipe”, Toast.LENGTH_SHORT).show();
    
    }
    
    return true;
    
    }
    
    return false;
    
    }
    
    }
    
    }
    

提交回复
热议问题