Store the start and end position of a mousedrag?

edited November 2017 in How To...

As the topic suggests, is there any way to get the start and end position of a single mouse drag?

Answers

  • Answer ✓

    In the Processing's website under reference, you can check the following key words: mousePressed() and mouseReleased(). Sample code below.

    PVector mStart;
    PVector mEnd;
    
    void setup(){}
    void draw(){println(if(mStart!=null) mStart.dist(mEnd))}
    void mousePressed(){mStart=new PVector(mouseX,mouseY);}
    void mouseReleased(){mEnd=new PVector(mouseX,mouseY);}
    

    Kf

  • edited November 2017 Answer ✓
    boolean mouseWasDown;
    float startEnd[] = new float[4];
    

    Start position:

    • on mousePressed
      • if mouseWasDown == false;
        • startEnd[0] = mouseX;
        • startEnd[1] = mouseY
        • mouseWasDown = true;

    End position:

    • on mouseReleased
      • startEnd[2] = mouseX;
      • startEnd[3] = mouseY;
      • mouseWasDown = false;

    Show it:

    line( startEnd[0], startEnd[1], startEnd[2], startEnd[3] );
    
  • edited December 2017

    Here is a more advanced example using the built-in mouseDragged -- it also saves a collection of previously drawn lines as children of a PShape, then displays the collection of past lines in the draw loop.

    If you wanted specifying lines to be based on a two-point clicking rather than dragging, you would need a state variable like an int to track which state you were in -- click the first point, click the second, or click again to save / clear, then click the first point....

    PVector mStart;
    PVector mEnd;
    boolean wasDown;
    PShape lines;
    
    void setup() {
      mStart = new PVector(0, 0);
      mEnd = new PVector(0, 0);
      lines = createShape();
      lines.setStroke(color(0,0,255));
      stroke(255,0,0);
      strokeWeight(2);
    }
    void draw() {
      background(0);
      // saved lines
      for(int i=0; i<lines.getChildCount(); i++){
        shape(lines.getChild(i));
      }
      // preview line
      line(mStart.x, mStart.y, mEnd.x, mEnd.y);
    }
    void mousePressed() {
      // start preview line
      mStart.set(mouseX, mouseY);
      mEnd.set(mouseX, mouseY);
    }
    void mouseDragged() {
      // update preview line
      mEnd.set(mouseX, mouseY);
    }
    void mouseReleased() {
      // create a line shape
      PShape newline = createShape();
      newline.beginShape();
      newline.stroke(0,255,0);
      newline.vertex(mStart.x, mStart.y);  
      newline.vertex(mEnd.x, mEnd.y);  
      newline.endShape();
      // save it
      lines.addChild(newline);
      // reset preview line
      mStart.set(-10, -10);
      mEnd.set(-10, -10);
    }
    

    MouseDrag--screenshot

Sign In or Register to comment.