Bouncing

Moderator: BenChang

Bouncing

Postby BenChang » Tue Nov 11, 2014 7:30 pm

Code: Select all
/* bouncing ball program */

float x;
float y;

float dx;
float dy;

float radius;
float dr;    // radius change

float c;    // background color;
float dc;   // change in background color;

void setup ()
{
   size(800,600);
   x=100;
   y=300;
   
   radius = 20;
   dr=0;
   
   dx=5;
   dy=0;
   
   c=0;
   dc=0;
   
}

void draw ()
{
 
   c=c+dc;
   if (c<0)
   {
      c=0;
      dc=0;
   }
   background(c);
   
   // update velocity
   
   dy=dy+.1;
   
   // update position
   
   x=x+dx;
   y=y+dy;

   
   if (y>600)
   {
     y=593;
     dy=-dy;
     c=50;
     dc=-5;
 
   }
   if (x>800 || x<0)
   {
     dx=-dx;
     c=50;
     dc=-5;
     
     
   }
   
   ellipse(x,y,radius,radius);
     
}
User avatar
BenChang
 
Posts: 176
Joined: Mon Jan 17, 2011 4:48 pm

Bouncing with mouse event, ArrayList, spawning

Postby BenChang » Tue Nov 11, 2014 7:31 pm

Bouncing2
Code: Select all
ArrayList<Ball> balls;

void setup()
{
  size(800,600); 
 
  balls = new ArrayList<Ball>();  // Create an empty ArrayList
 
 
}

void mouseReleased()
{
   balls.add(new Ball(mouseX,mouseY, (mouseX-pmouseX)/10.0, (mouseY-pmouseY)/10.0 ));
}

void draw()
{
  background(0);
 
  for (int i=0;i<balls.size();i++)
  {
     balls.get(i).draw();
  }
}



Ball
Code: Select all
class Ball
{
  float x;
  float y;

  float dx;
  float dy;

  float radius;
  float dr;    // radius change

  Ball (float x, float y, float dx, float dy)
  {
    this.x=x;
    this.y=y;
    radius = 20;
    dr=0;

    this.dx=dx;
    this.dy=dy;
   
   
  }

  void draw ()
  {
    // update velocity
    dy=dy+.1;
   
    // update position
    x=x+dx;
    y=y+dy;

    if (y>600)
    {
      y=593;
      dy=-dy;
    }
    if (x>800 || x<0)
    {
      dx=-dx;
    }
    ellipse(x, y, radius, radius);
  }
}

User avatar
BenChang
 
Posts: 176
Joined: Mon Jan 17, 2011 4:48 pm


Return to Art and Animation

Who is online

Users browsing this forum: No registered users and 1 guest

cron