Animated colors on a moving object

Hi! I’m trying to add animated colors to this ellipse that is moving back and forth when a key is pressed, but I can’t figure out what’s the problem in my code, as the color changes immediately from yellow to red when the key is pressed. I tried to change the colors by using variables to gradually change the rgb, but it doesn’t seem to work. I also wanted the ellipse to stop when the key is pressed, but it keeps going after I put the code for the colors in.

  int xBall = 400;
  int ballSpeed = 1;
  
  int r = 255;
  int g = 0;
  int b = 0;
  
  color ballColour = color(255, 255, 0);
  
 void setup(){
  size(800,800);
  }
  
 void draw(){
  background(100);
  fill(ballColour);
    ellipse(xBall,400,100,100);
  
xBall = xBall + ballSpeed;

  if (xBall > width || xBall < 0) {
    ballSpeed = ballSpeed * -1;
  
  }
 }


void keyPressed(){
 ballColour = color(r, g, b);
   if(g == 255 && b == 0)
  {
     g = g - 1;
     ballSpeed = 0;
  }
}

Can someone explain what I did wrong? I was planning to change the colors using lerpColor, but I don’t understand how it would work as an animation and would appreciate an example if my decision with the rgb variables wouldn’t work out.

there are different ways to solve it

  • to say g = g -1; is not of much use because g is 0 initially already and the range is from 0 to 255, so better say g=g+1;
    to say g = g -1; or g=g+1; in keyPressed is useless because keyPressed is called only once very briefly when a key is initially clicked. To have an animation that would be visible throughout, we should set a flag in keyPressed (to store the information that we had a key pressed) and read the flag / marker in draw() where the animation takes place. I named the flag changeColor.
  • ballSpeed was set to 0 inside an if-clause, that’s why we didn’t see a change.

I hope this helps.

Warm regards,

Chrisir


boolean changeColor = false; // No 

int xBall = 400;
int ballSpeed = 1;

int r = 255;
int g = 0;
int b = 0;

color ballColour = color(255, 255, 0);

void setup() {
  size(800, 800);
}

void draw() {
  background(100);

  ballColour = color(r, g, b);
  fill(ballColour);
  if (changeColor) {
    g = g + 1;
  }
  ellipse(xBall, 400, 100, 100);

  xBall = xBall + ballSpeed;

  if (xBall > width || xBall < 0) {
    ballSpeed = ballSpeed * -1;
  }
}

void keyPressed() {
  ballSpeed = 0;
  changeColor = true; // Yes
}
//