开发者

Multiple finger input for android development

After getting the calculator application to work I decided to try to create pong. There is a box in the center and two paddles on both ends. The phone is horizontal. I have the box bouncing off the walls and the paddle moves with me moving my finger down. My problem is i want to make it two player and i want to have multiple finger input for the game. I want one finger to move paddle 1 and the other to move paddle 2. So far this is my input code

@Override
 public boolean onTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        switch (action) {

        case MotionEvent.ACTION_MOVE: {
            // Find the index of the active pointer and fetch its position



           float p1y = ev.getY();

            if(ev.getX()<300)
            {
              player1y = p1y;
            }
            if(ev.getX()>300)
            {
              player2y = p1y;
            }

           //player1y = p1y;

            invalidate();
            break;
        }

        }
        return true;


    }

it resides in my surfaceview class. How can i modify the input method or completely get rid of it and change it to accomplish 开发者_高级运维my goal? Also sorry about my variables. Eclipse crashes a lot on me and my laptops touch panel tends to move my cursor so shorter variables seemed viable. p1y is the y of the touch. and player1y and player2y is the y positions of the player1 and player2 paddle.


A MotionEvent can hold multiple pointers. Use getPointerCount() to see how many pointers are touching the screen in the current event. There are alternate versions of getX and getY that take an index from 0-getPointerCount() - 1.

In a more complex app you would want to track fingers by pointer ID, but for something this simple where you are using a cutoff point on the screen you could do something like this in your ACTION_MOVE case:

int pointerCount = ev.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
    float x = ev.getX(i);
    float y = ev.getY(i);

    if (x < 300) {
        player1y = y;
    } else if (x > 300) {
        player2y = y;
    }
}

This post from the Android Developers Blog might help if you'd like more information: http://android-developers.blogspot.com/2010/06/making-sense-of-multitouch.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜