如何使用" Processing"绘制实现某些动画的动画矩形。

时间:2017-01-25 15:37:35

标签: processing

一个处理程序,它在窗口的左上角绘制一个矩形并向右移动直到它位于屏幕的右边缘。然后向下移动直到它在底部。然后将其移到左侧。最后,将其移回左上角并重新开始。

这是我未完成的代码,我不知道当它达到底线时如何让它向左移动:

void setup(){
size(500,500);
}
int x=0;
int y=0;
int dy=2;
int dx=2;
void draw(){


  x+=dx;


  if(x>=(width-50)){
    dx=0;
    y+=dy;
  } 
  if(y>=(height-50)){
    dy=0;
    x+=(-dx);
  }
  rect(x, y, 50,50, 7);
}

2 个答案:

答案 0 :(得分:1)

这是一个解决方案:

void setup(){
size(500,500);
}

int direction = 0;
int x = 0;
int y = 0;

void draw(){

  switch (direction)
  {
     case 0: //Right
        x += 1;        
        if (x+50 >= width) direction = 1;
     break;

     case 1: //Down
        y += 1;        
        if (y+50 >= height) direction = 2;
     break;

     case 2: //Left
        x -= 1;        
        if (x <= 0) direction = 3;
     break;

     case 3: //Up
        y -= 1;        
        if (y <= 0) direction = 0;
     break;
   }

   rect(x, y, 50,50, 7);
}

我没有测试它,但我希望一般的想法是明确的。

答案 1 :(得分:1)

除了@ Titulum的回答,我还建议您使用对象,因为它比按照您的方式处理点更容易。

Rectangle rect;
int direction;
int speed;

void checkDirections(){
switch (direction)
  {
     case 0: //Right
        rect.x += speed;        
        if (rect.x+rect.x1 >= width) direction = 1;
     break;

     case 1: //Down
        rect.y += speed;        
        if (rect.y+rect.y1 >= height) direction = 2;
     break;

     case 2: //Left
        rect.x -= speed;        
        if (rect.x <= 0) direction = 3;
     break;

     case 3: //Up
        rect.y -= speed;        
        if (rect.y <= 0) direction = 0;
     break;
   }
}


void setup(){
  size(500,500);
  direction = 0;
  speed = 5;
  rect = new Rectangle(0, 0, 50, 50);
}

void draw(){
  background(255);
  checkDirections();
  rect.drawRect();
}

class Rectangle{
  float x,y,x1,y1;
  Rectangle(float x, float y, float x1, float y1){
    this.x = x;
    this.y = y;
    this.x1 = x1;
    this.y1 = y1;
  }
  void drawRect(){
    fill(0);
    rect(x,y,x1,y1);
  }
}