【问题标题】:Change color on every 3rd bounce每 3 次反弹改变颜色
【发布时间】:2017-10-04 15:40:06
【问题描述】:

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

这是我当前的代码:

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

【问题讨论】:

  • 欢迎来到 SO。请访问help center 并阅读How to Ask。没有看到你的代码,我们怎么回答?
  • 好吧,你维护一个计数器为int counter = 0 或类似的东西,你每次反弹时都会增加(counter++;)。当它达到3 就像counter == 3 你改变颜色,因此使用if-statement。之后您重置计数器:counter = 0。为了提供进一步的帮助,您需要向我们提供您的代码的相关部分。
  • 这听起来像是可以使用取模运算符 (%) 来实现的,例如:stackoverflow.com/questions/9008522/…
  • 我投票结束这个问题,因为它不是一个真正的问题,只是一个需求转储。
  • @IvanSilvestrov 如果您不快速编辑和改进问题,问题很可能会被关闭。如果是这种情况,您当然可以重新创建问题,但内容会有所改进。因此请在之前仔细阅读How to ask,谢谢。

标签: java processing


【解决方案1】:

这很容易。您维护一个计数器,用于计算跳出次数。因此,您在每次反弹后将计数器增加一。如果它达到3,则更改颜色。之后,您重置计数器并重复。


因此,将此成员变量添加到您的类中(就像您已经对 xPos 和其他人所做的那样):

private int bounceCounter = 0;

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

这是修改后的 draw 方法,突出显示了更改和 cmets:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2015-03-07
    • 2014-12-31
    • 2022-11-12
    • 2017-11-20
    • 2018-12-15
    相关资源
    最近更新 更多