Why ellipse doesn't work?

Hello guys, I was playing a bit with processing and I tried to make a program which does a boucing shape.
This shape at the beginning is a square and when it touches the right edge it goes back but becoming a circle…buuut I cannot understand why it doesn’t work. Can you help me? I think is very stupid the solution but I can’t figure out.

thanks

float X;
float xspeed;
float C;

void setup(){
colorMode(HSB, 255, 255, 100);
background(255);

size(600,600);
X = 0;
C = 1;
}

void draw(){
fill(C+1, C+1, C+1, C+1);
C = C+1;
rectMode(CENTER);
rect(X, height/2, 50,50);
X = X + xspeed;

xspeed = 10;

if(X > width){
background(255);
fill(C+1, C+1, C+1, C+1);
C = C+1;
ellipse(X, height/2, 50,50);
xspeed = -10;
}
}

The first problem is that draw() is always setting the xspeed of your object back to 10. It’s doing this every frame. So once your object has hit the right edge, yes, it’s speed is set to -10, but only for one frame! The speed is set to 10 again when draw() runs again, and so it hits the right edge again, loops this behavior over and over, and thus gets stuck at the edge.

The second problem is that your code’s logic is all over the place. Let’s see if we can’t break your sketch down into more manageable sections.

First, we will simplify draw(). We will make it do four things:

  1. Move the object.
  2. Check if it hit the edge.
  3. If it did hit the edge, change the stored values that describe our object.
  4. Draw our object based on the values stored in the variables that describe it.

Thus our new draw() function looks like this:

void draw(){
  // Always start with a clean background!
  background(255);
  // Move the object.
  object_move();
  // Check if it hit an edge.
  if( object_did_hit_edge() ){
    // If it did, update its variables.
    object_on_edge_hit();
  }
  // Now finally, draw the object.
  object_draw();
}

Notice how that logic is crystal clear? I’m not even messing about with any variables in there! Next we need to write these functions:

void object_move(){
  // Add the speed to the position.
  object_x_position = object_x_position + object_speed;
}

boolean object_did_hit_edge(){
  return( object_x_position > width );
}

void object_on_edge_hit(){
  object_speed = -10;
  object_is_ellipse = true;
}

void object_draw(){
  if( object_is_ellipse ){
    ellipse( object_x_position, height/2, 20, 20);
  } else {
    rect( object_x_position, height/2, 20, 20);
  }
}

Notice how each of these functions is clear about what it does?
I glazed over the variables needed to know the object’s state:

float object_x_position = 0;
float object_speed = 10;
boolean object_is_ellipse = false;

Now try putting it all together yourself! Post the code of your new attempt at getting this to work.