Saving mouse position when creating a object in a array?

edited October 2015 in Questions about Code

So I'm making a knife carving kind of brush in processing.

My problem is it only draws a few rectangles and follows the mouse around kind of like the lag effect on a windows cursor. I'm guessing it has something to do with the way the object is being recorded and displayed.

I'm trying to get it so when I drag the mouse it "Paints" on the rectangles onto the sketch.

I have a class that defined a brush stroke, at the moment a rectangle.

class KnifeCut{ void Cut() { rect(mouseX, mouseY, 20, 20); } }

I'm using a array list to keep a record of brush strokes as the user drags there mouse.

ArrayList<KnifeCut> Cuts = new ArrayList<KnifeCut>();

When dragged it adds a new object like so.

void carvePumpkin() { Cuts.add(new KnifeCut()); } Then the display function is called in the draw function of my main processing tab

void carveDisplay() { for(int i = 0; i < Cuts.size(); i ++) { KnifeCut part = Cuts.get(i); part.Cut() } }

Tagged:

Answers

  • Difficult without seeing more code but it might be that you are creating hundreds of KnifeCuts and the list Cuts is getting very large. Try printing out the size of the list inside draw and see what you get

    println(Cuts.size() + " cuts");

  • Answer ✓

    I think the problem is within your KnifeCut-class. You are creating new KnifeCut-objects, but they are all the same, because they don't have properties. They only have a function, which draws a rectangle at mouse-position. What you need are class-variables that store the x/y position of the object and you have to set them inside of a constructor or manually.

    Example:

    ArrayList<KnifeCut> cuts;
    
    void setup() {
      size(300, 300);
      cuts = new ArrayList<KnifeCut>();
    }
    
    void draw() {
      background(200);
      for (int i = 0; i < cuts.size(); i ++) {
        KnifeCut part = cuts.get(i);
        part.display();
      }
    
      println(cuts.size());
    }
    
    class KnifeCut {
      // variables
      int x, y;
      // constructor
      KnifeCut() {
        x = mouseX;
        y = mouseY;
      }
    
      void display() {
        rect(x, y, 20, 20);
      }
    }
    
    void mouseDragged() {
      cuts.add(new KnifeCut());
    }
    

    btw.:It is a convention in most programming-languages, that class-names start with a capital letter and variables / functions start with a lower case letter. That doesn't affect the programm, it just to make your code better readable.

  • This worked, looks much better, I completely forgot about the constructor, thank so much.!

Sign In or Register to comment.