0

我正在玩Android 示例应用程序 Snake。原始蛇移动方向数学的代码如下。这很简单。方向由触摸在哪个象限根据屏幕中心确定。然而,这很粗糙。有时蛇在屏幕的右边缘,我想将它向左移动,但如果我的触摸在蛇的左侧但仍在右象限内,它的方向仍然是正确的。所以我需要一个以蛇头而不是屏幕中心为中心的更新方向数学。我没有成功进行此类更新。有数学好的人请帮忙。请注意,4 个象限被 2 条对角线分割。

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mSnakeView.getGameState() == SnakeView.RUNNING) {
            // Normalize x,y between 0 and 1
            float x = event.getX() / v.getWidth();
            float y = event.getY() / v.getHeight();

            // Direction will be [0,1,2,3] depending on quadrant
            int direction = 0;
            direction = (x > y) ? 1 : 0;
            direction |= (x > 1 - y) ? 2 : 0;

            // Direction is same as the quadrant which was clicked
            mSnakeView.moveSnake(direction);

        } else {
            // If the game is not running then on touching any part of the screen
            // we start the game by sending MOVE_UP signal to SnakeView
            mSnakeView.moveSnake(MOVE_UP);
        }
        return false;
    }
4

1 回答 1

0

编辑

@Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mSnakeView.getGameState() == SnakeView.RUNNING) {
            // Normalize x,y between 0 and 1
            float x = event.getX() / v.getWidth();
            float y = event.getY() / v.getHeight();
            Coordinate head = mSnakeTrail.get(0);

            // Direction will be [0,1,2,3] depending on quadrant
            int direction = 0;

            //This probably won't work very well
            //direction = (x > head.x) ? 1 : 0; //Right or left
            //direction = (y > head.y) ? 2 : 3; //Down or up

            //this will make sort of quadrants as well, but looked from the head
            direction = (x > head.x + 10) ? 1:(nowhere); //Right or nowhere (you'll have to see what to fill in instead of 0)
            direction = (x < head.x - 10) ? 0:(nowhere); //Left or nowhere
            direction = (y > head.y + 10) ? 2:(nowhere); //Down or nowhere
            direction = (y < head.y - 10) ? 3:(nowhere); //Up or nowhere

            // Direction is same as the quadrant which was clicked
            mSnakeView.moveSnake(direction);

        } else {
            // If the game is not running then on touching any part of the screen
            // we start the game by sending MOVE_UP signal to SnakeView
            mSnakeView.moveSnake(MOVE_UP);
        }
        return false;
    }

无论如何,我认为最好将蛇刷到你想要的方向。这是在手机上移动蛇的最简单方法。

因此,我建议不要添加 touchListener,而是添加一个gestureOverlay。您可以在此处查看如何添加手势:

http://developer.android.com/reference/android/gesture/GestureOverlayView.html

您也可以使用 GestureDetector。以下是 GestureDetector 的功能:

http://developer.android.com/reference/android/view/GestureDetector.html

这是一个例子:

https://stackoverflow.com/a/938657/2767703

于 2013-09-11T09:18:01.837 回答