How to remove previous shape after draw() in Processing

后端 未结 2 890
花落未央
花落未央 2021-01-21 00:47

I cant figure this out. I have a sketch with little rotating rectangles on it. They rotate on every draw(). However the previous rectangle remains visible. I tried moving backgr

2条回答
  •  -上瘾入骨i
    2021-01-21 01:43

    You've got a few things going on in your code that I've seen in your previous posts. The way you're doing your drawing doesn't make a ton of sense, and I'll explain why.

    Here's what most Processing sketches do:

    • Use the setup() function to setup any data structures you'll use in your program. Don't do any drawing from the setup() function.
    • Call background() every frame to clear out old frames.
    • Draw everything you want to be drawn in the frame in the draw() function.
    • Modify the data structures to change what you're drawing on the screen.

    Your code is a bit too long for an MCVE, so here's a little example that handles the drawing in a more standard way:

    ArrayList circles = new ArrayList();
    
    void setup() {
      size(500, 500);
      ellipseMode(RADIUS);
    
      //setup your data structures here
      circles.add(new PVector(250, 250));
    
      //don't do any drawing yet
    }
    
    void mousePressed() {
      //modify the data structure whenever you want to change what's on the screen
      circles.add(new PVector(mouseX, mouseY));
    }
    
    void keyPressed() {
      //modify the data structure whenever you want to change what's on the screen
      if (!circles.isEmpty()) {
        circles.remove(0);
      }
    }
    
    void draw() {
      //call background every frame to clear out old frames
      background(0);
    
      //draw everything
      for (PVector p : circles) {
        ellipse(p.x, p.y, 20, 20);
      }
    }
    

    Notice how this is different from what you're doing. Here's what you do:

    • You use the setup() function to setup your data structures, but then you draw the background and some of the objects to the screen.
    • You then don't call background() from draw(), so you're always stuck with whatever has already been drawn.
    • You then only draw a subset of what you want on the screen, so you can't redraw your whole scene.

    You have to modify your code to no longer draw anything from setup(), to call the background() function every frame, and to draw everything you want on the screen every frame.

提交回复
热议问题