每隔3次弹跳就会改变颜色

时间:2017-10-04 15:40:06

标签: java processing

我正在使用Processing; 我有一个球,当它击中边界时反弹,并将其颜色变为随机。现在我需要这个球在每三次弹跳时改变它的颜色。无法弄清楚该怎么做。

这是我目前的代码:

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);
    }    
}

1 个答案:

答案 0 :(得分:1)

这很容易。您维持计数器,计算反弹量。因此,每次反弹后,您都会将计数器增加1。如果它达到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;
        }
    }
}