有条件的循环 - 处理
Loops with a condition - Processing
假设一个球从屏幕上掉下来,一旦碰到边界就会重置:
float BallY = 50; // y value of the ball
float BallX = 260; // x value of the ball
void setup()
{
size(512, 348); //width and height of screen
}
void draw()
{
background(255);
fill(0);
ellipse(BallX, BallY, 15, 15); //ball that will fall
BallY++; //ball's y value increases each frame
if (BallY > height) //if ball's y value is greater than the screen
{
BallY = 0; //reset the y value of the ball back to 0
}
}
如何让我的 "if statement" 成为一个 "for loop",例如在屏幕左上角创建一个正方形,并在每次球到达终点时直接在其旁边创建另一个正方形屏幕?
因为我的逻辑是这样的:
for(float rectangleX=0; (rectangleX+20) <= width; rectangleX+=40){
for(float Bally=0; Bally<height; Bally++){
rect(rectangleX, 20, 20, 20);
但我知道这会在程序运行时创建一行矩形,而不是当球从屏幕上掉下来时一个一个地创建...我不确定如何将它们放在一起。那么解决这个问题的最佳方法是什么?
您缺少的一件事是记下球撞墙次数的计数器。
然后,通过从 0 到 counter - 1
的简单 for
循环,您可以绘制矩形。
您需要一些公式来计算他们的左 x 坐标,但这应该不会太难。
如上所述,您需要一个计数器。这是一个可能的解决方案:
float BallY = 50; // y value of the ball
float BallX = 260; // x value of the ball
int counter;
void setup()
{
size(512, 348); //width and height of screen
counter = 0;
}
void draw()
{
background(255);
fill(0);
ellipse(BallX, BallY, 15, 15); //ball that will fall
BallY++; //ball's y value increases each frame
if (BallY > height) //if ball's y value is greater than the screen
{
BallY = 0; //reset the y value of the ball back to 0
counter++;
}
for (int i = 0; i < counter; i++) {
rect(i * 20, 0, 20, 20);
}
}
希望这对您有所帮助。和平
编辑:
如果要更改矩形的起始 x 和 y 位置,可以在 for 循环中执行:
rect(100 + i * 20, 100, 20, 20);
假设一个球从屏幕上掉下来,一旦碰到边界就会重置:
float BallY = 50; // y value of the ball
float BallX = 260; // x value of the ball
void setup()
{
size(512, 348); //width and height of screen
}
void draw()
{
background(255);
fill(0);
ellipse(BallX, BallY, 15, 15); //ball that will fall
BallY++; //ball's y value increases each frame
if (BallY > height) //if ball's y value is greater than the screen
{
BallY = 0; //reset the y value of the ball back to 0
}
}
如何让我的 "if statement" 成为一个 "for loop",例如在屏幕左上角创建一个正方形,并在每次球到达终点时直接在其旁边创建另一个正方形屏幕?
因为我的逻辑是这样的:
for(float rectangleX=0; (rectangleX+20) <= width; rectangleX+=40){
for(float Bally=0; Bally<height; Bally++){
rect(rectangleX, 20, 20, 20);
但我知道这会在程序运行时创建一行矩形,而不是当球从屏幕上掉下来时一个一个地创建...我不确定如何将它们放在一起。那么解决这个问题的最佳方法是什么?
您缺少的一件事是记下球撞墙次数的计数器。
然后,通过从 0 到 counter - 1
的简单 for
循环,您可以绘制矩形。
您需要一些公式来计算他们的左 x 坐标,但这应该不会太难。
如上所述,您需要一个计数器。这是一个可能的解决方案:
float BallY = 50; // y value of the ball
float BallX = 260; // x value of the ball
int counter;
void setup()
{
size(512, 348); //width and height of screen
counter = 0;
}
void draw()
{
background(255);
fill(0);
ellipse(BallX, BallY, 15, 15); //ball that will fall
BallY++; //ball's y value increases each frame
if (BallY > height) //if ball's y value is greater than the screen
{
BallY = 0; //reset the y value of the ball back to 0
counter++;
}
for (int i = 0; i < counter; i++) {
rect(i * 20, 0, 20, 20);
}
}
希望这对您有所帮助。和平
编辑: 如果要更改矩形的起始 x 和 y 位置,可以在 for 循环中执行:
rect(100 + i * 20, 100, 20, 20);