theamycode
theamycode

Reputation: 219

Processing Shape Placement

I'm new to Processing and trying to figure out why this is happening under draw(). Based on where I place the creation of a rectangle, the circle does or does not appear. My goal is to get the drag-able circle in front of the rectangle.

int x;
int y;

public void setup()
{
    size(600, 600);
}

public void draw()
{
    background(255);
    // if timeLine() placed here, circle doesn't appear
    circle();
    timeLine();  // if timeline placed here, circle appears behind rectangle
}

public void circle()
{
    ellipse(this.x, height/2, 10, 10);
}

public void mouseDragged()
{
    translate(width/2, height/2);
    this.x = mouseX;
    this.y = mouseY;
}

public void mousePressed()
{
    translate(width/2, height/2);
    if (mouseY < height/2 + 10 && mouseY > height / 2 - 10) {
        this.x = mouseX;
    }
}

public void timeLine()
{
    translate(width/2, height/2);
    rectMode(CENTER);
    rect(0, 0, 2, 20);
}

Upvotes: 0

Views: 240

Answers (1)

v.k.
v.k.

Reputation: 2854

Your issue is that you are calling translate (from timeline() function) without the use of pusMatrix() popMatrix(), so those calls are affecting everything after it, until th end of draw(), where the matrix is reset.

If you pay attention, wit the lines ordered altered the circle is actually appearing at the bottom of the screen, translated half height down (plus the half height you used already in ellipse func).

To further understand those, I suggest this tutorial:

https://processing.org/tutorials/transform2d/

So You just need to encapsulate your transformations, like this:

int x;
int y;

public void setup()
{
  size(600, 600);
}

public void draw()
{
  background(255);
  timeLine();  
  circle();
}

public void circle()
{
  ellipse(this.x, height/2, 10, 10);
}

public void mouseDragged()
{
  translate(width/2, height/2);
  this.x = mouseX;
  this.y = mouseY;
}

public void mousePressed()
{
  translate(width/2, height/2);
  if (mouseY < height/2 + 10 && mouseY > height / 2 - 10) {
    this.x = mouseX;
  }
}

public void timeLine()
{
  //encapsulating matrix transformations
  //with push pop matrix
  pushMatrix();

  translate(width/2, height/2);
  rectMode(CENTER);
  rect(0, 0, 2, 20);

  popMatrix();
}

Upvotes: 1

Related Questions