Friday, August 19, 2011

[Processing] Transformation example in Processing

2D Transformations example:Online Demo
//@ http://scriptdemo.blogspot.com/
int numP;
myrose[] roses;
float rotAngle, myscale;
float shiftX, shiftY;

void setup()
{
  size(500,500);
  numP=36;
  smooth();
  roses=new myrose[numP];
  myscale=1;
  rotAngle=0;
  shiftX=width/2;
  shiftY=height/2;
  frameRate(30);
  for (int n=0; n<numP; n++)
  {
    roses[n]=new myrose();
  }
  noStroke();
}
void draw()
{
  background(255);
  translate(shiftX,shiftY);
  if (!mousePressed)
  {
    rotAngle=rotAngle+PI/100;
  }
  rotate(rotAngle);
  scale(myscale);
  pushMatrix();
  for (int n=0; n<numP; n++)
  {
   roses[n].myrose();
   roses[n].setangle(n*TWO_PI/numP);
   roses[n].showit();
  }
  popMatrix();
}

class myrose
{
  float myangle;
  int nres=20;
  float[] xx=new float[nres*2+1];
  float[] yy=new float[nres*2+1];
  float rr=0.4*width;
  float rr05=rr/2;
  float rry=0.1*rr;

  void myrose()
  {
     for (int n=-nres; n<=nres; n++)
     {
        xx[n+nres]=rr05+n*rr05/nres;
        yy[n+nres]=rry*sin(n*TWO_PI/nres);
     }
  }
  void showit()
  {
    pushMatrix();
    rotate(myangle);
    for (int n=0; n<xx.length; n++)
    {
      fill(n*255/xx.length,127);
      ellipse(xx[n],yy[n],5,5);
    }
    popMatrix();
  }
  void setangle(float ang)
  {
    myangle=ang;
  }
}

void mouseDragged()
{
  if (mouseButton==CENTER)
  {
    shiftX+=(mouseX-pmouseX);
    shiftY+=(mouseY-pmouseY);
  } else if (mouseButton==LEFT) {
    float d0=(pmouseX-width/2)*(pmouseX-width/2)+(pmouseY-height/2)*(pmouseY-height/2);
    float dc=(mouseX-width/2)*(mouseX-width/2)+(mouseY-height/2)*(mouseY-height/2);
    myscale=(sqrt(dc)-sqrt(d0));
  }
}

No comments:

ShowCalendar