首页 > 解决方案 > 在处理过程中控制水滴数组的 Y 值

问题描述

我制作了很多线条(水滴)落下的动画;通过单击鼠标左键,您只需减慢它们的速度。我还想做的是在它们下落时控制它们的 Y 值:当我用鼠标单击时,它们都会跟随它。

Drop[] drops = new Drop[270]; // array 

void setup() {
     size(640, 360); // size of the window
     for (int i = 0; i < drops.length; i++) {
         drops[i] = new Drop();
    }
}

void draw() {

    background(52);

    for (int i = 0; i < drops.length; i++) {
        drops[i].fall(); 
        drops[i].show(); 
        drops[i].noGravity(); 
    }
}

和 Drop 类:

class Drop {
    float x = random(width); // posizione x di partenza
    float y = random(-180,-100); // posizione y di partenza
    float yspeed = random(2,7); // velocità random

    void fall() { 
        y += yspeed;

        if (y > height) { // riposizionamento delle gocce
            y = random(-180,-100);
        }
    }

    void noGravity(){ //
        if(mousePressed && (mouseButton == LEFT)){
            y -= yspeed*0.75;
        }

        if(mousePressed && (mouseButton == RIGHT)){
              this.y = mouseY + yspeed;
        }
    }

    void show() { // funzione per l'aspetto delle gocce
        stroke(52, 82, 235);
        line(x,y,x,y+20);
    }
}

我正在谈论的函数是 noGravity(),但是当我单击鼠标右键时,而不是跟随我的鼠标,所有的水滴都排成一行。有什么简单的建议吗?谢谢你们!!!

标签: javaarraysprocessing

解决方案


右键单击时更改 y 位置与更改水滴移动的速度不同。你可能只是没有注意到。

在这里,尝试更改noGravity()这些行的右键单击部分:

yspeed = abs(yspeed); //this is so the drops behaves normally again when you stop right clicking
if(mousePressed && (mouseButton == RIGHT)){
  if (mouseY < this.y) { //this makes the drops go toward the mouse position
    yspeed = yspeed * -1; //going up is negative speed
  }
}

这有点酷。请注意,如果您按住右键单击,当您移动鼠标时,水滴会尝试使用自己的速度跟随。我不知道你在做什么,但我喜欢它。

我不确定想要的结果,所以如果我误解了,请告诉我。


推荐阅读