开发者

Simply multi touch programming for Android

I've scoured the internets trying to find an answer for this, but all the tutorials I've read seem to significantly over complicate my little problem. Basical开发者_如何学Pythonly, I have a ship on the left side of the screen that moves up and down if you drag your finger up and down on the left side of the screen, and fires a missile if you touch anywhere on the right side of the screen.

public boolean onTouchEvent(MotionEvent event)
{
    if (event.getX() < getWidth()/2)
    {   
        if (shipY < event.getY())
            shipY = shipY + 10;
        if(shipY > event.getY())
            shipY = shipY - 10;
    }

    if (event.getX() >= getWidth()/2)
    {
        if(!missile)
        {
            missile = true;
            missileY = shipY;
            missileX = shipX;
        }
    }
    return true;
}

Right now I can only fire the missile if I stop moving the ship. Thank you much!


I contributed to an explanation of this problem yesterday: Touch more one button at once

TL;DR - You can't touch two Views at the same time. You need to combine them into a custom ViewGroup and dispatch the touch events yourself if you want to accomplish concurrent touches on multiple View objects.


If your ship and missile happen to be in the same View, then you can add an onTouchListener to that view which will handle multiple touch. (It would be your own class, which implements View.onTouchListener)

Here's a skeleton of the method you'll need to override in the onTouchListener:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction() & MotionEvent.ACTION_MASK) {

        case MotionEvent.ACTION_DOWN:
            //first finger went down
            break;

        case MotionEvent.ACTION_MOVE:
            //a touch placement has changed
            break;

        case MotionEvent.ACTION_UP:
            //first finger went up
            break;

        case MotionEvent.ACTION_CANCEL:
            //gesture aborted (I think this means the finger was dragged outside of the touchscreen)
            break;

        case MotionEvent.ACTION_POINTER_DOWN:
            //second finger (or third, or more) went down.
            break;

        case MotionEvent.ACTION_POINTER_UP:
            //second finger (or more) went up.
            break;

            default: break;
        }
        return true;
    }

You can get more detail on these cases (and others you might want to use) at http://developer.android.com/reference/android/view/MotionEvent.html .

About how you handle your logic - in the case of sane play, your ACTION_DOWN, or "first finger" would probably correspond to the player touching the ship, and the ACTION_POINTER_DOWN where they want to shoot a missile. But remember to handle cases where the player may touch the "missile side" of the screen first, and then touch the ship to move it afterwards.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜