Draggable Objects in Processing

I’ve been playing around in Processing to create a synth which is controlled by linking nodes together. These nodes are basically circles, with information displayed within them.

One thing I ran into right away which, in my opinion, should be a Processing core class is a lack of a Draggable class. With the help of some googling, I eventually cooked up my own, which performs quickly no matter the framerate.

This code makes use of Vectors, so it should be a very quick bit of code. I’ve had no problems using it.

Vector nodes;
  1. boolean drag_locked;
  2. void setup()
  3. {
  4.   size(700, 500, P2D);
  5.   smooth();
  6.   nodes = new Vector();
  7.   drag_locked = false;
  8.   nodes.add(new Node(20, 20,20));
  9.   nodes.add(new Node(50, 50,20));
  10.   frameRate(30);
  11. }
  12.  
  13. void draw()
  14. {
  15.   smooth();
  16.   background(20);
  17.   for(int i=0;i<nodes .size();i++) {
  18.     Node temp = (Node)nodes.get(i);
  19.     temp.draw();
  20.   }
  21. }
  22. class Node
  23. {
  24.   float x,y,mo_x,mo_y;
  25.   int radius;
  26.   boolean locked;
  27.   Node(float x, float y, int radius){
  28.     this.x = x;
  29.     this.y = y;
  30.     this.radius = radius;
  31.   }
  32.   void draw(){
  33.     fill(0,255,0);
  34.     ellipse(x, y, radius*2, radius*2);
  35.     if(over() && keyPressed){
  36.       nodes.remove(nodes.indexOf(this));
  37.     }
  38.     if(mousePressed && over() && !drag_locked){
  39.       mo_x = x-mouseX;
  40.       mo_y = y-mouseY;
  41.       locked = true;
  42.       drag_locked = true;
  43.     }
  44.     if(!mousePressed){
  45.       locked = false;
  46.       drag_locked = false;
  47.     }
  48.     if(locked){
  49.       x = mouseX+mo_x;
  50.       y = mouseY+mo_y;
  51.     }
  52.   }
  53.   boolean over(){
  54.     if(dist(x, y, mouseX, mouseY) < radius){
  55.       return true;
  56.     }
  57.     return false;
  58.   }
  59.  
  60. }

This will set up two nodes on your screen which are draggable, complete with offsetting and so on to make them behave perfectly. Hope this helps!