Saturday, February 5, 2011

2D random walk using Processing

//To show 2D random [some limitation in the code] walk using Processing
// Copyright by http://scriptdemo.blogspot.com

myParticles[] myP;
int numP=2;
boolean IsLine=false;

void setup()
{
  size(400,400);
  background(0);
  myP=new myParticles[numP];

  for (int i=0; i<numP; i++)
  {
    myP[i]= new myParticles();
    myP[i].x=random(100,300);
    myP[i].y=random(100,300);
  }
  frameRate(50);
}

void draw()
{
  for(int i=0; i<numP; i++)
  {
    myP[i].move();
    if (ceil(myP[i].x)== width | ceil(myP[i].y) == height)
    {
      noLoop();
    }
  }
}
void mouseClicked()
{
  background(0);
}
void mouseReleased()
{
  for(int i=0; i<numP; i++)
  {
    myP[i].setxy(mouseX,mouseY);
  }
  IsLine=!IsLine;
  loop();
}

class myParticles
{

  public float x0;
  public float y0;
  public float x;
  public float y;

  public void myParticles()
  {
  }
  public void setxy(float tmpx, float tmpy)
  {
    x=tmpx;
    y=tmpy;
  }

  public void move()
  {
    for ( int i=20; i<=60; i=i+10 )
    {
      float tmpx, tmpy;
      float myangle;
      float dx=5;
      float dy=5;
      x0=x;
      y0=y;
      myangle=(i+floor(random(-5,5)))*PI/180.0;
      tmpx=dx*random(-1,1);
      tmpy=dy*random(-1,1);
      x=x+tmpx*cos(myangle)-tmpy*sin(myangle);
      y=y+tmpy*cos(myangle)+tmpx*sin(myangle);
      if ( x<0 ) { x=0.0; }
      if ( x>width ) { x=width; }
      if ( y<0 ) {y=0.0;}
      if ( y>height ) { y=height; }

      int rr=floor(random(255));
      int rg=floor(random(255));
      int rb=floor(random(255));
      stroke(rr,rr,rb);
      if (IsLine)
        {
          line(x0,y0,x,y);
        }
       else
      {
        point(x,y);
      }
    }
  }
}



No comments:

ShowCalendar