我需要将两个椭圆都从X_start移到X_END,然后同时移回X_START

时间:2018-10-05 17:27:34

标签: processing

final int X_START = 1 ;
final int Y_START = 250 ;
final int X_END = 500 ;
final int Y_END = 250 ; 
final int SPEED_FACTOR = 5 ;

int xCenter;
int yCenter;
int ellip1Center;
int ellip2Center;

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

void draw(){
  calculateDimension();
  drawSpaceship();
  moveSpaceship();
}

void calculateDimension(){
  xCenter = X_START;
  yCenter =(Y_START +Y_END)/2;
  ellip1Center = xCenter +50;
  ellip2Center = xCenter +20;
}

void drawSpaceship(){
  background(0);
  ellipse(ellip1Center, yCenter, 20, 20); 
  ellipse(ellip2Center, yCenter, 30, 30);
}

void moveSpaceship(){
  xCenter+= SPEED_FACTOR ;
}

我需要moveSpaceship命令的帮助。 我需要将两个椭圆都从X_start移到X_END,然后同时移回X_START

1 个答案:

答案 0 :(得分:0)

将函数calculateDimension拆分为2个函数。一个函数用于初始化参考位置(xCenteryCenter),而on函数用于更新椭圆的位置(ellip1Centerellip2Center)。添加一个新变量speed,该变量保存椭圆的当前速度,如果椭圆到达轨道的末尾,则可能会变为负速度。

int speed;
void initDimension(){
    xCenter = X_START;
    yCenter =(Y_START +Y_END)/2;
    speed   = SPEED_FACTOR;
}

void calculateDimension(){
    ellip1Center = xCenter +50;
    ellip2Center = xCenter +20;
}

致电initDimension中的setupcalculateDimension中的draw

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

void draw(){
    calculateDimension();
    drawSpaceship();
    moveSpaceship();
}

如果到达轨道的终点或起点,则通过更改变量speed来改变椭圆的方向:

void moveSpaceship(){
    xCenter += speed;
    if (xCenter >= X_END-65) speed = -SPEED_FACTOR;
    if (xCenter <= 0) speed = SPEED_FACTOR;
}