Issue
I am making a racing game with 2 cars, each of which to be controlled by a different player on the same device. I used the OnTouchEvent method to move the cars by drag and drop. I can't test the code on my laptop because my laptop can't do multi-touch and only allows me to control one car at a time (I only have the emulator from Android Studio, and no physical Android device). So what I currently know is that this code allows the cars to be moved one at a time. I was wondering if my code actually makes it so that the cars can be moved at the same time (which is what I want)or if they can only be moved one at a time:
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
// press down
case MotionEvent.ACTION_DOWN:
// conditionals check which car is tapped on
if (car.getCollisionShape().contains((int)event.getX(), (int)event.getY())) {
car.setActionDown(true);
} else if (car2.getCollisionShape().contains((int)event.getX(), (int)event.getY())) {
car2.setActionDown(true);
}
break;
// finger moved along screen
case MotionEvent.ACTION_MOVE:
// moves the cars horizontally where the fingers are moved
if(car.getActionDown()) {
car.setPosition(event.getX(), car.y, true);
} else if (car2.getActionDown()) {
car2.setPosition(event.getX(), car2.y, true);
}
break;
// finger released
case MotionEvent.ACTION_UP:
// conditionals check which car is tapped on
if (car.getCollisionShape().contains((int)event.getX(), (int)event.getY())) {
car.setActionDown(false);
} else if (car2.getCollisionShape().contains((int)event.getX(), (int)event.getY())) {
car2.setActionDown(false);
}
break;
}
return true;
}
Inside the ACTION_DOWN, a car's boolean, which signals if the car is currently being hold down or not, becomes true. Inside, the ACTION_MOVE, the car's location is shifted to wherever the event.getX() and event.getY() are
Solution
Unfortunately, your code doesn't seem to be designed properly for handling multi-touch operations. To make multi-touch work, pointer-IDs
are required, which can be obtained by using MotionEvent.getPointerId().
Steps to handle multi-touch gestures are roughly outlined as follows.
- Get pointer-ID in
ACTION_DOWN
and map the ID to the car instance according to hit test result. - And in subsequent actions (
ACTION_MOVE
,ACTION_UP
), determine for which car the MotionEvent is targeted, based on the pointer-ID. And then apply changes to the relevant car instance.
See the official training documentation for handling multi-touch gestures.
By the way, emulator has a little function to simulate multi-touch by mouse (mainly for testing pinch and spread gestures). You may be able to utilize it for testing your app. See Pinch and spread
section in this table to know how to use it.
Answered By - ardget
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.