在mousePressed中编辑函数



我是处理的初学者,试图创建一个移动的云草图。它们将出现在mouseClick上,并在屏幕上水平移动。

void mousePressed() {
int newCloud {
xpos: mouseX;
ypos: mouseY;
}
clouds.push(newCloud);
}

这是我无法修复的区域,正在尝试解决鼠标按下的部分。

这是我的完整代码!这似乎是一个简单的修复方法,但我尝试了很多方法来重写它,但都没有成功。

int[] clouds;
int cloudx;
int cloudy;
int xpos, ypos;
void setup() {
size(600, 600);
int cloudx=mouseX;
int cloudy=mouseY;
}
void draw() {
background(100);
for (int i = 0; i < clouds.length; i++) {
int[] currentObj = clouds[i];
cloud(currentObj.xpos, currentObj.ypos, currentObj.size);
currentObj.xpos += 0.5;
currentObj.ypos += random(-0.5, 0.5);
if (clouds[i].xpos > width+20) {
clouds.splice(i, 1);
}
}
}
void makeCloud (int x, int y){
fill(250);
noStroke();
ellipse(x, y, 70, 50);
ellipse(x + 10, y + 10, 70, 50);
ellipse(x - 20, y + 10, 70, 50);
}

void mousePressed() {
int newCloud {
xpos: mouseX;
ypos: mouseY;
}
clouds.push(newCloud);
}

我试着做了一个新函数,虽然云不会显示,但我也试着调用makeCloud函数,尽管我知道我需要在这个新函数中更新。总的来说,我需要帮助如何在mousePressed函数中为newCloud编写此语句。

由于多种原因,您的代码无法修复。

  • int[]云将为单个整数数组创建引用,而不是对象
  • void makeCloud(int x,int y({…},只会画一些椭圆
  • clouds.splice(i,1(在Array中根本不起作用

这是您的问题的工作重建:

ArrayList<Cloud> clouds = new ArrayList<Cloud>();
void setup() {
size(600, 600);
}
void draw() {
background(100);
drawClouds(clouds);
removeExcessClouds(clouds);
}

/**
** Cloud class
**/
class Cloud {
float xPos;
float yPos;
Cloud(float x, float y) {
xPos = x;
yPos = y;
}
void draw() {
fill(250);
noStroke();
ellipse(xPos, yPos, 70, 50);
ellipse(xPos + 10, yPos + 10, 70, 50);
ellipse(xPos - 20, yPos + 10, 70, 50);
}

void positionUpdate(float deltaX) {
xPos += deltaX;
yPos += random(-0.5, 0.5);    
}
}

void drawClouds(ArrayList<Cloud> cds) {
float wind = 0.5;
for (Cloud cd : clouds) {
cd.draw();
cd.positionUpdate(wind);
}
}

void removeExcessClouds(ArrayList<Cloud> cds) {
int cdAmount = clouds.size();
for (int i = 0; i<cdAmount; i++) {
if (clouds.get(i).xPos > width+20) {
clouds.remove(i);
cdAmount = clouds.size();
}
}
}

void mousePressed() {
clouds.add(new Cloud(mouseX, mouseY));
println(mouseX + ", " + mouseY + " : " + clouds.size());
}

注:

  • 全局列表初始化:
    ArrayList clouds=new ArrayList((
  • 列出正确的迭代:
    for(Cloud-cd:clouds({foo(cd(;}
  • 在Cloud中绘制方法
  • 在调用方法时传递值

因此,现在您可以迭代对象列表,并在每个Cloud中调用一个draw方法。

正如在另一个答案中所说,您需要重构代码以使用对象。

这看起来像是JS对象文字的一个语句——Java不使用它们。

int newCloud {
xpos: mouseX;
ypos: mouseY;
}

您需要实例化一个类


Cloud myCloud = new Cloud(0,5); // You create a new variable of the Cloud type and initialize it with a new Cloud object (essentially calling the constructor)
class Cloud{
int posX, posY;
Cloud(int px, int py){ // This is called a constuctor and its the way a new instance is created
this.posX = px;
this.posY = py;
}
}

对于云阵列,您需要云阵列列表:

ArrayList<Cloud> clouds = new ArrayList<Cloud>();

mousePressed事件中,您不只是将新云添加到arraylist:

clouds.add(myCloud);

最新更新