我正在玩Android sample app Snake。原始蛇移动方向数学的代码如下。这很简单。方向由基于屏幕中心的触摸所在的象限确定。然而,这很粗糙。有时候蛇在屏幕的右边缘,我想向左移动,但如果我的触摸位于蛇的左侧但仍在右边的象限内,它的方向仍然是正确的。所以我需要一个以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;
}
答案 0 :(得分: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;
}
无论如何,我认为将蛇划向你想要的方向会更好。 这是在手机上移动蛇的最简单方法。
因此,我建议添加一个gestureOverlay,而不是添加一个touchListener。 你可以在这里查看如何添加手势:
http://developer.android.com/reference/android/gesture/GestureOverlayView.html
您也可以使用GestureDetector。以下是GestureDetector的功能:
http://developer.android.com/reference/android/view/GestureDetector.html
这是一个例子: