当我更改 window 大小时,我的动画球不会在中间交叉

My animation balls doesn't cross at the middle when i change the window size

有两条球道,每条球道都有一个球...当动画开始时,它会在默认 window 大小的情况下穿过中间。当我更改 window 大小时,它不会在中间交叉。过去几周我一直在努力解决这个问题。

float x = 0.4*width/8; 
float y = 0.4*height/8; 

void setup(){
    size(600,600);
    background(#C8F5F2);
    frameRate(10);
}

void draw(){

    fill(255);
    noStroke();
    rectMode(CENTER);
    rect(width/2, 0, width/8, height*2);  //vertical lane 
    rect(0, height/2, 2*width, height/8); //horizontal lane 

    fill(255,0,0,100);
    ellipse( width/2, x, 0.8*width/8, 0.8*width/8); //vertical ellipse

    fill(0,255,0,100);
    ellipse( y, height/2, 0.8*height/8, 0.8*height/8); //horizontal 
    //ellipse

    if(x < height - 0.4*width/8){
        x = x + width/45;
    }

    if(y < width - 0.4*height/8){
        y = y + height/20;
    }
}

我希望我的回答是 "cross the balls on middle at any window size"

如果球要从中间穿过,那么它们必须同时通过不同的方式。

球的半径是:

float radius1 = 0.4*height/8; 
float radius2 = 0.4*width/8;

第一个球的路径在x轴上,从x=radius1x=width-radius1。 第二个球的路径在y轴上,从y=radius2y=height-radius2.

所以“球的下一个位置可以通过以下方式计算:

x += (width - 2.0*radius1) / steps;
 y += (height - 2.0*radius2) / steps;

其中 steps 是每个球从开始到结束应该走的步数。

另外注意,x轴是从左到右,y轴是从上到下。看例子:

float x, y; 
float steps = 20.0;

void setup(){
    size(800,300);
    background(#C8F5F2);
    frameRate(10);

    x = 0.4*height/8;
    y = 0.4*width/8;
}

void draw(){

    float radius1 = 0.4*height/8; 
    float radius2 = 0.4*width/8; 

    fill(255);
    noStroke();
    rectMode(CENTER);
    rect(width/2, 0, width/8, height*2);  //vertical lane 
    rect(0, height/2, 2*width, height/8); //horizontal lane 

    fill(255,0,0,100);
    ellipse(x, height/2, radius1*2.0, radius1*2.0); //vertical ellipse

    fill(0,255,0,100);
    ellipse(width/2, y, radius2*2.0, radius2*2.0); //horizontal 

    if(x < width - radius1){
        x += (width - 2.0*radius1) / steps;
    }
    if(y < height - radius2){
        y += (height - 2.0*radius2) / steps;
    }
}

.i need another thing to know and that is how to declare specific key to speed up and speed down the balls. like "Pressing the UP key results in doubling of speed and pressing the DOWN key results in halving of speed.

当按下一个键时,keyPressed() is executed. Use keyCode 评估是否按下了 UP 或 DOWN 并更改 steps

void keyPressed() {
    if (keyCode == DOWN)
        steps /= 2.0;
    else if (keyCode == UP)
        steps *= 2.0;
}