How to create a mouse trace

edited March 2014 in How To...

Hello everyone! I am new to Processing and I am currently taking a course on it. I need to create a project and I don't really know how to code my idea and I didn't really find anything about it on the internet. I am trying to create something like a transparent green trace behind the mouse(maybe with the mouseDragged function..). Does anyone know how to do that? I seriously need help for my project! :)

Answers

  • ArrayList<PVector> al = new ArrayList();void setup(){size(400,400);stroke(255);}void draw(){
    al.add(new PVector(mouseX,mouseY,0));while(al.size()>255)al.remove(0);background(0);for(int i=0;
    i<al.size()-1;i++){stroke(0,i,0);line(al.get(i).x,al.get(i).y,al.get(i+1).x,al.get(i+1).y);}}
    
  • Here are 2 versions: 1 using Queue<PVector>, and the other 2 int[].
    Check the array version online: :D

    studio.processingtogether.com/sp/pad/export/ro.9ldYvJUyiXGzi/latest


    Mouse Trace Queue:


    /**
     * Mouse Trace Queue (v1.0)
     * by GoToLoop (2014/Mar)
     *
     * forum.processing.org/two/discussion/3437/how-to-create-a-mouse-trace
     */
    
    import java.util.Queue;
    import java.util.ArrayDeque;
    
    static final int MAX = 1<<7;
    final Queue<PVector> coords = new ArrayDeque(MAX);
    
    void setup() {
      size(800, 600, JAVA2D);
      colorMode(RGB, MAX-1);
      frameRate(60);
      smooth(4);
      strokeWeight(1);
    
      mouseX = width>>1;
      mouseY = height>>1;
    
      for ( int i = 0; i++ != MAX; 
        coords.add(new PVector(mouseX, mouseY)) );
    }
    
    void draw() {
      clear();
    
      PVector p = coords.remove();
      p.set(mouseX, mouseY);
      coords.add(p);
    
      p = coords.element();
      int i = 0;
    
      for (PVector c: coords) {
        stroke(0, i++, 0);
        line(p.x, p.y, p.x = c.x, p.y = c.y);
      }
    }
    


    Mouse Trace Array:


    /**
     * Mouse Trace Array (v1.0)
     * by GoToLoop (2014/Mar)
     *
     * forum.processing.org/two/discussion/3437/how-to-create-a-mouse-trace
     *
     * studio.processingtogether.com/sp/pad/export/ro.9ldYvJUyiXGzi/latest
     */
    
    final static int NUM = 0300, NEWEST = NUM - 1;
    final int[] x = new int[NUM], y = new int[NUM];
    
    void setup() {
      size(800, 600, JAVA2D);
      colorMode(RGB, NEWEST);
      frameRate(60);
      smooth(4);
      strokeWeight(1);
    
      mouseX = width>>1;
      mouseY = height>>1;
    
      for (int i = NUM; i-- != 0; x[i] = mouseX, y[i] = mouseY);
    }
    
    void draw() {
      background(0);
    
      for ( int i = 0; i != NEWEST;) {
        stroke(0, i, 0);
        line(x[i], y[i], x[i] = x[i + 1], y[i] = y[++i]);
      }
    
      x[NEWEST] = mouseX;
      y[NEWEST] = mouseY;
    }
    

Sign In or Register to comment.