Get touch that started/ended with touchStated() / touchEnded()

Hi,
can I somehow get the touch pointer that was added/removed in the touchStarted() or touchEnded() functions?

Hi @JoLi,

Hmmm! It is a bit weird…

You can also uses the touchStarted/Ended with TouchEvent parameter, but the way it is implemented don’t give you the nearest expectation (actually the event which one has started/ended). Therefore it seems you need to implement the handling on your own.

Here is a quick hack which do so … (quickly tinkered on my mobile, which I really hate to do :grimacing: :slight_smile:, so weakly tested but should work and could be used as a starting point…)

ArrayList<Integer> touchMap;
color[] cols;

void setup() {
  fullScreen();
  touchMap = new ArrayList<Integer>();
  cols = new color[5];
  colorMode(HSB, 5, 1, 1);
  for (int i=0; i<cols.length; i++)
    cols[i] = color(i, 1, 1);
}

void touchStarted() {
  for (TouchEvent.Pointer p : touches) {
    if (!touchMap.contains(p.id)) {
      touchMap.add(p.id);
      println("touch started: " + p.id);
    }
  }
}

void touchEnded() {
  for (int i=touchMap.size()-1; i>=0; i--) {
    boolean found=false;
    for (TouchEvent.Pointer p : touches) {
      if (touchMap.get(i)==p.id) {
        found=true;
        break;
      }
    }
    if (!found) {
      println("touch ended: " + touchMap.get(i));
      touchMap.remove(i);
    }
  }
}

void draw() {
  background(0);
  noStroke();
  for (TouchEvent.Pointer p : touches) {
    fill(cols[p.id%5]);
    ellipse(p.x, p.y, 250, 250);
  }
}

Cheers
— mnse

PS: Apropos… If you only need one touch, not multi touch, you can simply use mouseX/mouseY for starting and ending position… :nerd_face:

PPS: if your Processing for Android using java8+ the checks inside the touchStarted/Ended could be written more elegant with the new features :smile:

2 Likes

oh tysm!
this is exactly what I needed!
My project is basically a touchpad:
the app on the phone detects 1 touched finger: action 1 is executed from a companion program on a pc.
the app detects a second finger: action 2 is also executed
finger 1 is not touching anymore: action 1 is stopped, action 2 is still executed
finger 2 is also not touching anymore: action 2 is also stopped.

if it’s done, i’ll maybe post another reply to this thread with the repo(s) for the code

1 Like