我正在玩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;
}