Android - 触摸屏模拟实现方向键

改写Android的Snake例子,使之运行于我的三星手机上。判断规则如下:如果x方向移动距离大于y方向,则认为是水平移动,反之则是上下移动。如果水平移动,x移动正距离x-x0>0 则认为向右移动,负距离x-x0<0 则认为向左移动;上下移动的判断同理。

代码如下,需要注意的是MotionEvent的ACTION_DOWN, ACTION_UP 是这么理解的:
ACTION_DOWN - A pressed gesture has started, the motion contains the initial starting location.

ACTION_UP - A pressed gesture has finished, the motion contains the final release location as well as any intermediate points since the last down or move event.

ACTION_MOVE - A change has happened during a press gesture (between {@link #ACTION_DOWN} and {@link #ACTION_UP}). The motion contains the most recent point, as well as any intermediate points since the last down or move event. -

简而言之,ACTION_DOWN, ACTION_UP 类似于Javascript里面键盘事件OnKeyDown, OnKeyUp 或鼠标事件OnMouseDown, OnMouseUp, 而不是说手指往上划拉或往下划拉了一下。

	/**
* Re write onKeyDown() for SAMSUNG
*/
public boolean onTouchEvent(MotionEvent event) {
// Set the game status to running
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mMode == READY | mMode == LOSE) {
initNewGame();
setMode(RUNNING);
update();
return true;
}

if (mMode == PAUSE) {
setMode(RUNNING);
update();
return true;
}
}

float x = event.getX();
float y = event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mX = x;
mY = y;
update();
return true;
case MotionEvent.ACTION_UP:
float dx = x - mX;
float dy = y - mY;
if (Math.abs(dx) >= TOUCH_TOLERANCE
|| Math.abs(dy) >= TOUCH_TOLERANCE) {

if (Math.abs(dx) >= Math.abs(dy)) { // move from left -> right
// or right -> left
if (dx > 0.0f) {
turnTo(EAST);
} else {
turnTo(WEST);
}

} else { // move from top -> bottom or bottom -> top
if (dy > 0.0f) {
turnTo(SOUTH);
} else {
turnTo(NORTH);
}
}
update();
return true;
}
}

return super.onTouchEvent(event);
}

private void turnTo(int direction) {
if (direction == WEST & mDirection != EAST) {
mNextDirection = WEST;
}

if (direction == EAST & mDirection != WEST) {
mNextDirection = EAST;
}

if (direction == SOUTH & mDirection != NORTH) {
mNextDirection = SOUTH;
}

if (direction == NORTH & mDirection != SOUTH) {
mNextDirection = NORTH;
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值