D4rWiNS D4rWiNS - 4 months ago 25
Java Question

Getting the last finger touching the screen

I need to do controls, and I am having problem with multi touch.

The concept is easy:


  • if the user touches the left (half of the screen) side the ship go to the left

  • if the user touches the right (half of the screen) side the ship go to the right.



The problems come when the user does the following:


  • Put finger on left side

  • Without removing left finger, put finger on the right side

  • remove left finger

  • Put again left finger (my code won't recognize it, there is the problem)



I want a code that only get the 'X' position of the last finger in the screen

My actual code:

@Override
public boolean onTouchEvent(MotionEvent event)
{
int index = MotionEventCompat.getPointerCount(event) - 1;

float x = (int) MotionEventCompat.getX(event, index);
@SuppressWarnings("deprecation")
int ancho = AEngine.display.getWidth();

switch (MotionEventCompat.getActionMasked(event))
{
case MotionEvent.ACTION_DOWN:
if (gameView != null)
gameView.touchNave(x, ancho);
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (gameView != null)
gameView.touchNave(x, ancho);
break;
case MotionEvent.ACTION_MOVE:
if (gameView != null)
gameView.touchNave(x, ancho);
break;

case MotionEvent.ACTION_UP:
Nave.estado = AEngine.NAVE_STAY;
break;
case MotionEvent.ACTION_POINTER_UP:
Nave.estado = AEngine.NAVE_STAY;
break;
}


return false;
}

Answer

I made it by using a LinkedHashMap and using the last item of it code:

LinkedHashMap<Integer, Float> al = new LinkedHashMap<Integer, Float>();
@Override
public boolean onTouchEvent(MotionEvent event)
{
    int index = MotionEventCompat.getActionIndex(event);
    int id = event.getPointerId(index);

    float x = (int) MotionEventCompat.getX(event, index);


    @SuppressWarnings("deprecation")
    int ancho = AEngine.display.getWidth();

    switch (MotionEventCompat.getActionMasked(event))
    {
        case MotionEvent.ACTION_DOWN:
            anadir(id,x);               
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            anadir(id,x);
            break;

        case MotionEvent.ACTION_UP:
            al.remove(id);
            break;
        case MotionEvent.ACTION_POINTER_UP:         
            al.remove(id);
            break;
    }

    if(al.size() > 0)
    {
        if (gameView != null)
            gameView.touchNave(getX(al), ancho);
    }
    else 
    {
        Nave.estado = AEngine.NAVE_STAY;
    }

    return false;
}
public float getX(LinkedHashMap<Integer,Float> map) {
    Iterator<Map.Entry<Integer,Float>> iterator = map.entrySet().iterator();
    float x = 0;
    while (iterator.hasNext()) {
        x = iterator.next().getValue();
    }
    return x;
}

public void anadir(int id,float x)
{
    if (al.size() > 0 || !al.containsKey(id))
    {
        al.put(id, x);  
        Log.e("WTF",Integer.toString(id)+ "aƱadido");
    } 
}
Comments