调用该参数时如何更改函数?
我想创建一个可以生成两个球以不同速度上升的函数。我使用了称为更改
的速度的参数,以及其x坐标的另一个参数,称为x
,以免它们源自同一位置。这是一个处理中的代码,因此内置了椭圆,大小,填充,笔触,设置和DRAW功能。
如果我调用该功能,则可以正常工作,并且球根据我设置的速度移动。但是,如果我两次调用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);
}
I want to create a function that can generate two balls that rise at different speeds. I used the parameters of the speed in which it rises called change
and another parameter of its x coordinates called x
, so that they don't originate from the same place. This is a code in processing, so the ellipse, size, fill, stroke, setup and draw functions are built in.
If I call the function, it works, and the ball moves according to the speed that I set. However, if I call the risingball()
function twice, two balls are generated, but both move at the speed that is called with the second executed function. In this case, two balls were generated at x coordinates 150 and 450. The first ball was supposed to move at speed y-10
, and the second ball at speed y-5
, but both are moving at y-5
.
Therefore, they move, but the whole purpose of the code which is making it change doesn't work.
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使您使用函数两次,该函数也会修改相同的一个
y
变量:因为您想以独立的速度移动两个球大家都需要两个独立的
y
变量(每个球一个)。您可以使用两个独立的
y
变量,但还需要修改该函数,以免更改相同的数据。一个选项可能是使用AY参数并返回修改后的数据:另一个变体可能是简单地使用该函数渲染球,但请保留
y
变量更新功能外部的更新:另一个选项是使用类,尽管我不确定您是否有机会玩这些。万一:
Even though you're using the function twice, that function modifies the same one
y
variable:Because you want to move two balls at independent speeds you all need two independent
y
variables (one for each ball).You could use two independent
y
variables but you'd also need to modify the function so it doesn't change the same data. One option could be using a y argument and returning the modified data:Another variant might be to simply use the function to render the ball, but keep the
y
variable updates outside the function:Yet another option is using classes, though I'm not sure if you had a chance to play with these yet. Just in case: