gpt4 book ai didi

java - 每第三次反弹改变颜色

转载 作者:行者123 更新时间:2023-12-02 12:10:43 25 4
gpt4 key购买 nike

我正在使用处理;我有一个球,当它碰到边界时会弹起并将其颜色更改为随机。现在我需要这个球每三次弹跳改变一次颜色。不知道该怎么做。

这是我当前的代码:

float xPos;// x-position
float vx;// speed in x-direction
float yPos;// y-position
float vy;// speed in y-direction
float r;
float g;
float b;

void setup()
{
size(400, 300);
fill(255, 177, 8);
textSize(48);

// Initialise xPos to center of sketch
xPos = width / 2;
// Set speed in x-direction to -2 (moving left)
vx = -2;
yPos = height / 2;
vy = -1;
}

void draw()
{
r = random(255);
b = random(255);
g = random(255);

background(64);

yPos = yPos + vy;
// Change x-position on each redraw
xPos = xPos + vx;

ellipse(xPos, yPos, 50, 50);
if (xPos <= 0)
{
vx = 2;
fill(r, g, b);
} else if (xPos >= 400)
{
vx = -2;
fill(r, g, b);
}
if (yPos <= 0)
{
vy = 1;
fill(r, g, b);
} else if (yPos >= 300)
{
vy = -1;
fill(r, g, b);
}
}

最佳答案

这很容易。您维护一个计数器来计算退回数量。因此,每次反弹后,计数器都会加一。如果达到 3,则更改颜色。之后重置计数器并重复。

<小时/>

因此,将此成员变量添加到您的类中(就像您对 xPos 等所做的那样):

private int bounceCounter = 0;

它引入了变量bounceCounter,最初将0作为值。

这是修改后的 draw 方法,其中突出显示了更改和注释:

void draw() {
// New color to use if ball bounces
r = random(255);
b = random(255);
g = random(255);

background(64);

yPos = yPos + vy;
// Change x-position on each redraw
xPos = xPos + vx;

ellipse(xPos, yPos, 50, 50);

// Variable indicating whether the ball bounced or not
boolean bounced = false;

// Out of bounds: left
if (xPos <= 0) {
vx = 2;
bounced = true;
// Out of bounds: right
} else if (xPos >= 400) {
vx = -2;
bounced = true;
}

// Out of bounds: bottom
if (yPos <= 0) {
vy = 1;
bounced = true;
// Out of bounds: top
} else if (yPos >= 300) {
vy = -1;
bounced = true;
}

// React to bounce if bounced
if (bounced) {
// Increase bounce-counter by one
bounceCounter++;

// Third bounce occurred
if (bounceCounter == 3) {
// Change the color
fill(r, g, b);

// Reset the counter
bounceCounter = 0;
}
}
}

关于java - 每第三次反弹改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com