Processing编程【3】

carrunning

Car myCar;
PFont font;

void setup() {
  size(400, 400);
  myCar = new Car();
  //background(255);
  font = createFont("Courier-Bold", 18);
  textFont(font);
  textAlign(CENTER, CENTER);
}

void draw() {
  background(255);
  myCar.drive();
  myCar.display();
  myCar.make();
  myCar.model();
}

汽车的类:

class Car {
  color c;
  float x;
  float y;
  float speed;
  void make(){
   text("make:Ford.",width/2,height*4/5);};
  void model(){
   text("model:Kuga.",width/2,height*6/8);};

  Car() {
    c = color(0);
    x = width/2;
    y = height/2;
    speed = 2;
  }  

  void display() {
    rectMode(CENTER);
    fill(c);
    rect(x, y, 20, 10);
  }

  void drive() { 
    x = x + speed;
    if (x > width)
      x = 0;
  }
} // end of class

小球弹动

主函数

void setup()
{
  size(500,600);
  b=new ball(80,10,10,(int)random(252));
  b.play();
}
void draw(){
  background(0, 0, 255);
  b.play();
}

小球类


class ball {
  int rad;    // radius
  int x, y;    // center's position of the ball
  int speedx=3; // for horizontal speed
  int speedy=3; // for vertical speed
  color c;    // color of the ball

  // constructor for initialization
  ball(int r, int spx, int spy, int co) { 

    rad=r;
    x=spx;
    y=spy;
    c=co;
  }

  // display a ball with the given x, y and rad, filled with c
  void display() { 
    colorMode(HSB, 360, 255, 100);
    fill(c,255,255);
    noStroke();
    ellipse(x, y, rad*2, rad*2);
  }

  // set the new position according to speedx and speedy 
  // and check if a bounce happens
  void moveBall() { 


    if (y>=height-rad)
    {
      speedx=(int)random(1,4);
      speedy=-3;
    } else if (x>=width-rad) {
      speedx=-3;
      speedy=(int)random(1, 4);
    }
    else if(y<=rad)
    {
    speedy=3;}
    else if(x<=rad)
    {speedx=(int)random(1,4);
  speedy=(int)random(1,4);}

    x=x+speedx;
    y=y+speedy;
  }


  // display a ball and let it move
  void play() { 
    display();
    moveBall();
  }
}
原文地址:https://www.cnblogs.com/hitWTJ/p/9865446.html