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
。
答案 0 :(得分:0)
将函数calculateDimension
拆分为2个函数。一个函数用于初始化参考位置(xCenter
,yCenter
),而on函数用于更新椭圆的位置(ellip1Center
,ellip2Center
)。添加一个新变量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
中的setup
和calculateDimension
中的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;
}