用帆布查看手势似乎不起作用

时间:2015-12-18 21:57:26

标签: android canvas view

我在弄清楚手势时遇到了麻烦。如何使用滑动/手势使蛇移动? 我是android的新手,我似乎做错了什么。 请帮忙。

PS:我刚刚借用了一些onFling()方法。

这是我的代码:

package com.nethoinkz.snake;

import android.content.Context;
import android.graphics.Canvas;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by kenneth on 12/17/2015.
 */
public class GameView extends View implements GestureDetector.OnGestureListener {

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private Snake snake;

    public GameView(Context context, Snake snake) {
        super(context);
        this.snake = snake;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        snake.setCanvasX(canvas.getWidth());
        snake.setCanvasY(canvas.getHeight());

        canvas.drawBitmap(snake.getSnakeHead().getImg(), snake.getSnakeHead().getX(), snake.getSnakeHead().getY(), null);
        for(SnakeBody sb : snake.getSnakeBodies()) {
            canvas.drawBitmap(sb.getImg(), sb.getX(), sb.getY(), null);
        }
        snake.move();
        postInvalidateDelayed(200);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {System.out.println(" in onFling() :: ");
        if (Math.abs(e1.getY() - e2.getY()) < SWIPE_MAX_OFF_PATH) {
            //left
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                snake.goLeft();
            }
            //right
            else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                snake.goRight();
            }
        }
        else if (Math.abs(e1.getX() - e2.getX()) < SWIPE_MAX_OFF_PATH) {
            //up
            if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                snake.goUp();
            }
            //down
            else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                snake.goDown();
            }
        }
        else {
            return false;
        }
        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

onDown(MotionEvent e)更改return false;return true;