我刚刚制作了一个快速系统,它有两个操纵杆(一个用于移动,一个用于射击),它们可以与多点触控配合使用。
但是,当您同时使用两者时,它们会相互干扰(您放慢速度、奇怪地转弯等),我想知道这是我的手机(Nexus One,2.3.6)的问题还是代码的问题:
public void handleEvent(MotionEvent event) {
final int action = event.getAction();
switch(action & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN: {
pointerID = event.getPointerId(0);
int tx = (int) event.getX(event.findPointerIndex(pointerID));
int ty = (int) event.getY(event.findPointerIndex(pointerID));
boolean reset = true;
if(tx >= (x - radius * 2) && (tx <= (x + radius * 2))) {
if(ty >= (y - radius * 2) && (ty <= (y + radius * 2))) {
dx = (tx - x);
dy = (ty - y);
reset = false;
}
}
if(reset) pointerID = -1;
break;
}
case MotionEvent.ACTION_POINTER_DOWN: {
if(pointerID == -1) {
final int pointerIndex = event.getActionIndex();
pointerID = event.getPointerId(pointerIndex);
int tx = (int) event.getX(pointerIndex);
int ty = (int) event.getY(pointerIndex);
if(tx >= (x - radius * 2) && (tx <= (x + radius * 2))) {
if(ty >= (y - radius * 2) && (ty <= (y + radius * 2))) {
dx = (tx - x);
dy = (ty - y);
}
}
}
break;
}
case MotionEvent.ACTION_MOVE: {
if(pointerID != -1) {
final int pointerIndex = event.findPointerIndex(pointerID);
int tx = (int) event.getX(pointerIndex);
int ty = (int) event.getY(pointerIndex);
if(tx >= (x - radius * 2) && (tx <= (x + radius * 2))) {
if(ty >= (y - radius * 2) && (ty <= (y + radius * 2))) {
dx = (tx - x);
dy = (ty - y);
}
}
}
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = event.getActionIndex();
final int id = event.getPointerId(pointerIndex);
if(id == pointerID) {
dy = 0;
dx = 0;
pointerID = -1;
}
break;
}
case MotionEvent.ACTION_UP: {
if(-1 != pointerID) {
dy = 0;
dx = 0;
pointerID = -1;
}
break;
}
}
}
重要笔记:
每个操纵杆都是一个类,每个操纵杆都会调用handleEvent 方法。
pointerID
是属于每个操纵杆的 int
dy
并且dx
只是到操纵杆中心的距离。