2017-10-04 7 views
0

処理中です。 私はボールがボーダーに当たったときにバウンスし、その色をランダムに変えます。今度は3回目のバウンスごとに色を変えるためにこのボールが必要です。それをどうやって行うのか分かりません。3回ごとのバウンスで色を変更してください

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

へようこそ:

は、ここで強調表示の変更やコメントと修正draw方法です。 [help]にアクセスして[ask]を読んでください。コードを見ずに、どうすれば答えることができますか? –

+0

まあ、カウンターを 'int counter = 0'やそれがバウンスするたびに増加するもの(' counter ++; ')のように維持します。 'counter == 3 'のように' 3 'に達すると、色を変えるので、' if'文を使用してください。その後、カウンタ: 'counter = 0'をリセットします。 **あなたの**コード**の関連部分を**私たちに提供する必要があることをさらに助けるため。 – Zabuza

+0

これは、モジュラス演算子(%)を使用して実現できるようです。例:https://stackoverflow.com/questions/9008522/insert-tr-after-every-third-loop –

答えて

1

それは非常に簡単です:

は、ここに私の現在のコードです。 カウンタは、バウンスの数です。したがって、毎回のバウンス後にカウンタを1ずつ増やします。 3に達すると色が変わります。その後、カウンターをリセットして繰り返します。 (すでにxPosと他の人と行ったように)


したがって、あなたのクラスには、このメンバ変数を追加します。

private int bounceCounter = 0; 

値として0を保持する最初に変数bounceCounterを紹介しています。 SO

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; 
     } 
    } 
} 
関連する問題