如何使参数在调用函数时更改它



我想创建一个函数,可以生成两个以不同速度上升的球。我使用了上升速度的参数change和x坐标的另一个参数x,这样它们就不会来自同一个地方。这是一个正在处理的代码,因此椭圆、大小、填充、笔划、设置和绘制功能都内置在中

如果我调用函数,它就会工作,球会按照我设定的速度移动。然而,如果我调用risingball()函数两次,就会生成两个球,但它们都以第二个执行函数调用的速度移动。在这种情况下,在x坐标150和450处生成了两个球。第一个球本应以速度y-10移动,第二个球以速度y-5移动,但两者都以y-5移动。

因此,它们会移动,但使其发生更改的代码的全部目的并不起作用。

void setup(){
size(600,600);
}
float y = 600;
void risingball(float change, float x){
noStroke();
fill(30,0,30);
y = y-change;
ellipse(x,y, 50,50);
}
void draw(){
background(255);
risingball(10, 450);
risingball(5, 250);
}

即使您使用函数两次,该函数也会修改相同的一个y变量:

risingball(10, 450); // modifies y first
risingball(5, 250);  // modifies the same y again (when it shouldn't)

因为你想以独立的速度移动两个球,所以你都需要两个独立的y变量(每个球一个(。

您可以使用两个独立的y变量,但也需要修改函数,使其不会更改相同的数据。一种选择可以是使用y参数并返回修改后的数据:

float y1 = 600;
float y2 = 600;
void setup(){
size(600,600);
}
float risingball(float change, float x, float y){
noStroke();
fill(30,0,30);
y = y-change;
ellipse(x,y, 50,50);
return y;
}
void draw(){
background(255);
y1 = risingball(10, 450, y1);
y2 = risingball(5, 250, y2);
}

另一种变体可能是简单地使用函数来渲染球,但在函数之外保持y变量更新:

float y1 = 600;
float y2 = 600;
void setup(){
size(600,600);
}
void risingball(float x, float y){
noStroke();
fill(30,0,30);
ellipse(x,y, 50,50);
}
void draw(){
// update data
y1 = y1 - 10;
y2 = y2 - 5;
//render
background(255);
risingball(450, y1);
risingball(250, y2);
}

还有一种选择是使用类,尽管我不确定你是否有机会玩这些。以防万一:

// RisingBall(float argX, float argY, float argChange, float argSize)
RisingBall ball1 = new RisingBall(450, 600, -10, 50);
RisingBall ball2 = new RisingBall(250, 600, -5, 50);
void setup(){
size(600,600);
noStroke();
fill(30,0,30);

}
void draw(){
background(255);
ball1.updateAndDraw();
ball2.updateAndDraw();
}
class RisingBall{

float x;
float y;
float vy;

float diameter;

RisingBall(float argX, float argY, float argChange, float argSize){
x = argX;
y = argY;
vy = argChange;
diameter = argSize;
}

void updateAndDraw(){
// update
y += vy;
// optional: reset Y
if(y < -diameter){
y = height;
}
// draw
ellipse(x, y, diameter, diameter);
}

}

最新更新