源程序是这样的,初学者,改了好长时间,不过还是会偶尔出状况,还望有高手指教。
本来是想写好几个圆在里边的,可能力有限,还不会用数组
int direction1=1;
int direction2=1;
int direction3=1;
int direction4=1;
int d1,d2;
int r=120;
float x1=600,y1=300;
float x2=400,y2=100;
float speed1=20;
float speed2=15;
float speed3=13;
float speed4=18;
float s1,s2;
void setup(){
frameRate(60);
size(1200,600);
smooth();
}
void draw(){
background(0);
//边界反弹
if((x1+r/2>width)||(x1-r/2<0)){
direction1*=-1;
}
if((y1+r/2>height)||(y1-r/2<0)){
direction2*=-1;
}
if((x2+r/2>width)||(x2-r/2<0)){
direction3*=-1;
}
if((y2+r/2>height)||(y2-r/2<0)){
direction4*=-1;
}
//两圆相撞反弹,速度和方向都交换
if(dist(x1,y1,x2,y2)<120){
d1=direction1;
d2=direction2;
direction1=direction3;
direction2=direction4;
direction3=d1;
direction4=d2;
s1=speed1;
s2=speed2;
speed1=speed3;
speed2=speed4;
speed3=s1;
speed4=s2;
}
//圆心坐标轨迹
x2+=speed3*direction3;
y2+=speed4*direction4;
x1+=speed1*direction1;
y1+=speed2*direction2;
//显示
fill(0,191,255);
ellipse(x1,y1,r,r);
fill(0,255,0);
ellipse(x2,y2,r,r);
}